某计算机网络中存在 nn 个路由,每个路由代表一个子网。路由之间有 n - 1n−1 条互通关系,使得这 nn 个网络之间任意两个网络都可以直接联通,或者通过其他网络间接连通。
为了测试组建的网路的性能,假设相邻的路由之间的数据传输需要一单位时间,现在需要知道任意两个路由之间传输数据最多需要多长时间。
输入格式
第一行一个整数 n(2 \le n \le 50000)n(2≤n≤50000) 表示网络中路由个数。
接下来 n - 1n−1 行,每行输入 u, v(1 \le u,v \le n)u,v(1≤u,v≤n) ,表示路由 u, vu,v 相连。
输出格式
输出一行表示答案。
样例输入
8 6 3 3 7 3 4 7 5 5 1 6 8 5 2
样例输出
5
解题说明:一树的最大直径是从任意节点出发dfs最深的一个节点,然后从这个中间节点出发dfs最深的距离。
AC代码:
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
using namespace std;
const int MAXN=50000;
vector<int>ve[MAXN+5];
bool mark[MAXN+5];
int note,num=0;
void dfs(int x,int ans){
if(num<ans){
note=x;
num=ans;
}
for(int i=0;i<ve[x].size();i++){
if(!mark[ve[x][i]]){
mark[ve[x][i]]=true;
dfs(ve[x][i],ans+1);
mark[ve[x][i]]=false;
}
}
return ;
}
int main(){
int n;cin>>n;
for(int i=1;i<n;i++){
int ip1,ip2;cin>>ip1>>ip2;
ve[ip1].push_back(ip2);
ve[ip2].push_back(ip1);
}
mark[1]=true;
dfs(1,0);
memset(mark,false,sizeof(mark));
num=0;
dfs(note,0);
cout<<num<<endl;
return 0;
}