C2. Brain Network (medium)

Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v (1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.

In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.

Input
The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains a b it connects (1 ≤ a, b ≤ n and a ≠ b).

Output
Print one number – the brain latency.

Examples
input
4 3
1 2
1 3
1 4
output
2
input
5 4
1 2
2 3
3 4
3 5
output
3
求树上最长路径:

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const int maxn=1e5+5;
vector<int> G[maxn];
int ans,last;

void dfs(int cur,int pre,int len){
    if(len>ans){
        ans=len;
        last=cur;
    }
    for(int i=0;i<G[cur].size();i++){
        int to=G[cur][i];
        if(to!=pre)
        dfs(to,cur,len+1);
    }
}

int main(){
     ios_base::sync_with_stdio(0);
    // cin.tie(0);
     int n,m;
     while(cin>>n>>m){
            for(int i=0;i<maxn;i++)
            G[i].clear();
        for(int i=0,x,y;i<m;i++){
            cin>>x>>y;
            G[x].push_back(y);
            G[y].push_back(x);
        }
        ans=0;
        dfs(1,0,0);
        ans=0;
        dfs(last,0,0);
        cout<<ans<<"\n";
     }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值