NEFU 1301 树的直径(bfs)

树的直径

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值