树的直径
Problem:1301
Time Limit:1000ms
Memory Limit:65535K
Description
树的直径是指树的最长简单路。我们通常通过两遍BFS or DFS得到。即先任选一个起点BFS or DFS找到最长路的终点,再从终点进行BFS or DFS,则第二次找到的最长路即为树的直径。现给出一棵树,求树的直径。
Input
第一行输入一个整数 T( T <= 10 ) ,代表样例的个数。 对于每组样例 第一行输入树的顶点数 N (1<=N<=1e5) 接下来 N - 1 行,每行包含两个数 x y ,代表顶点 x 和 y 之间有一条边(x,y <= N)
Output
一个整数,树的直径的长度
Sample Input
2 9 1 2 1 3 2 4 2 5 3 6 6 8 6 7 8 9 9 1 2 1 3 2 4 2 5 3 6 3 7 6 8 6 9
Sample Output
7 6
题意:中文题。
思路:用两次bfs来遍历树,第二次得到的就是树长度最大的。也就是树的直径。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int inf=0x3f3f3f3f;
int maxi;
int maxn;
struct node
{
vector<int> next;
}q[100005];
int d[100005];
void bfs(int now)
{
queue<int> que;
que.push(now);
while(!que.empty())
{
int u=que.front();
que.pop();
int len=q[u].next.size();
for(int i=0;i<len;i++)
{
if(d[q[u].next[i]]!=inf) continue;
d[q[u].next[i]]=d[u]+1;
if(d[q[u].next[i]]>maxn)
{
maxn=d[q[u].next[i]];
maxi=q[u].next[i];
}
que.push(q[u].next[i]);
}
}
}
int main()
{
int t,n,x,y;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(q,0,sizeof(q));
for(int i=1;i<=n-1;i++)
{
scanf("%d%d",&x,&y);
q[x].next.push_back(y);
q[y].next.push_back(x);
}
memset(d,inf,sizeof(d));
maxn=0;
d[1]=0;
bfs(1);
maxn=0;
memset(d,inf,sizeof(d));
d[maxi]=0;
bfs(maxi);
printf("%d\n",maxn+1);
}
return 0;
}