1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include <bits/stdc++.h> #define N 100005 #define ios ios::sync_with_stdio(0),cin.tie(0) using namespace std; int n,start,dis[N]; bool visit[N]; vector<int>edge[N];
int dfs(int id,int cur_dis){ if(visit[id])return 0; visit[id] = 1; int len = edge[id].size(),max_len=0; for(int i=0;i<len;i++){ int next = edge[id][i]; if(visit[next])continue; dis[next] = cur_dis+1; int temp = dfs(next,cur_dis+1); max_len = max(max_len,temp); } return max_len+1; }
int main(){ ios; cin>>n; for(int i=0;i<n-1;i++){ int a,b;cin>>a>>b; edge[a].push_back(b); edge[b].push_back(a); } start = 0; memset(visit,0,sizeof(visit)); int distance = dfs(2,0);distance--; for(int i=0;i<n;i++){ if(dis[i]==distance){ start = i; break; } } memset(visit,0,sizeof(visit)); cout<<dfs(start,0)-1<<endl; }
|