HDU4607+BFS
1 /* 2 bfs+求树的直径 3 关键:if k<=maxs+1 直接输出k-1; 4 else: k肯定的是包括最长路。先从最长路的起点出发,再走分支,最后到达最长路的终点。 5 因此是2*(k-(maxs+1))+maxs; 6 */ 7 #include<stdio.h> 8 #include<string.h> 9 #include<stdlib.h> 10 #include<algorithm> 11 #include<iostream> 12 #include<queue> 13 #include<map> 14 #include<math.h> 15 using namespace std; 16 typedef long long ll; 17 //typedef __int64 int64; 18 const int maxn = 100005; 19 const int inf = 0x7fffffff; 20 const double pi=acos(-1.0); 21 const double eps = 1e-8; 22 struct Node{ 23 int v,next; 24 }edge[ maxn<<1 ]; 25 int cnt,head[ maxn ]; 26 int vis[ maxn ],dis[ maxn ]; 27 int maxs,maxNode; 28 void init(){ 29 cnt = 0; 30 memset( head,-1,sizeof( head ) ); 31 } 32 void addedge( int a,int b ){ 33 edge[ cnt ].v = b; 34 edge[ cnt ].next = head[ a ]; 35 head[ a ] = cnt++; 36 37 edge[ cnt ].v = a; 38 edge[ cnt ].next = head[ b ]; 39 head[ b ] = cnt++; 40 } 41 void bfs( int s,int n ){ 42 memset( vis,0,sizeof( vis ) ); 43 vis[ s ] = 1; 44 queue<int>q; 45 q.push( s ); 46 //for( int i=0;i<=n;i++ ) 47 //dis[ i ] = inf; 48 dis[ s ] = 0; 49 maxs = 0; 50 while( !q.empty() ){ 51 int cur = q.front(); 52 q.pop(); 53 if( dis[ cur ]>maxs ){ 54 maxs = dis[ cur ]; 55 maxNode = cur; 56 } 57 //maxs = max( maxs,dis[ cur ] ); 58 for( int i=head[ cur ];i!=-1;i=edge[ i ].next ){ 59 int v = edge[ i ].v; 60 if( vis[ v ]==1 ) continue; 61 vis[ v ] = 1; 62 dis[ v ] = dis[ cur ]+1; 63 q.push( v ); 64 } 65 } 66 return ; 67 } 68 int main(){ 69 int T; 70 scanf("%d",&T); 71 while( T-- ){ 72 int n,m; 73 scanf("%d%d",&n,&m); 74 int a,b; 75 init(); 76 int N = n-1; 77 while( N-- ){ 78 scanf("%d%d",&a,&b); 79 addedge( a,b ); 80 } 81 bfs( 1,n ); 82 bfs( maxNode,n ); 83 //maxs=the R of the tree 84 while( m-- ){ 85 scanf("%d",&b); 86 if( b<=maxs+1 ) printf("%d\n",b-1); 87 else printf("%d\n",2*(b-maxs-1)+maxs); 88 } 89 } 90 return 0; 91 }
keep moving...