本文主要是介绍【HDU】5102 The K-th Distance bfs,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
传送门:【HDU】5102 The K-th Distance
题目分析:思路秒出,5101写完不到20分钟这题就AC了。。将所有点扔进队列中,记录前驱,步数,每次扩展的时候不走前驱,这样就相当于n棵树同时在扩展。注意到一条路径会被重复走两次,所以k*2,ans/2。注意姿势不对就会MLE。
代码如下:
#include <map>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std ;typedef long long LL ;#define rep( i , a , b ) for ( int i = ( a ) ; i < ( b ) ; ++ i )
#define For( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i )
#define rev( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i )
#define clr( a , x ) memset ( a , x , sizeof a )const int MAXN = 100005 ;
const int MAXE = 200005 ;struct Node {int v , p , d ;Node () {}Node ( int v , int p , int d ) : v ( v ) , p ( p ) , d ( d ) {}
} ;struct Edge {int v , n ;Edge () {}Edge ( int v , int n ) : v ( v ) , n ( n ) {}
} ;Node Q[2100005] ;
Edge E[MAXE] ;
int H[MAXN] , cntE ;
int head , tail ;
LL ans ;
int n , k ;void clear () {ans = 0 ;cntE = 0 ;clr ( H , -1 ) ;
}void addedge ( int u , int v ) {E[cntE] = Edge ( v , H[u] ) ;H[u] = cntE ++ ;
}void bfs () {int cnt = 0 ;head = tail = 0 ;For ( i , 1 , n ) Q[tail ++] = Node ( i , 0 , 0 ) ;while ( head != tail ) {Node x = Q[head ++] ;int u = x.v , p = x.p ;for ( int i = H[u] ; ~i ; i = E[i].n ) {int v = E[i].v ;if ( v != p ) {Q[tail ++] = Node ( v , u , x.d + 1 ) ;ans += x.d + 1 ;//printf ( "%d->%d %d %d\n" , u , v , cnt , x.d + 1 ) ;++ cnt ;if ( cnt == k ) return ;}}}
}void solve () {int u , v ;clear () ;scanf ( "%d%d" , &n , &k ) ;k *= 2 ;rep ( i , 1 , n ) {scanf ( "%d%d" , &u , &v ) ;addedge ( u , v ) ;addedge ( v , u ) ;}bfs () ;printf ( "%I64d\n" , ans / 2 ) ;
}int main () {int T ;scanf ( "%d" , &T ) ;while ( T -- ) solve () ;return 0 ;
}
这篇关于【HDU】5102 The K-th Distance bfs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!