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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include<stdio.h> #include<set> #include<iostream> #include<stack> #include<cstring> #include<cmath> #include<vector> #include<algorithm> typedef long long ll; typedef long double ld; typedef double db; #define io_opt ios::sync_with_stdio(false);cin.tie(0);cout.tie(0) using namespace std; const int mod=998244353; int mo(ll a,int p){ return a>=p?a%p:a; } inline int rd() { int x = 0, f = 1; char ch; while (ch < '0' || ch > '9') { if (ch == '-')f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); } return f * x; } int n,ans; struct E{ int u,v,nex; }e[200020]; int g[100020]; int f[100020]; int dfs(int x){ int mx1=0,mx2=0; for(int i=g[x];i>0;i=e[i].nex){ if(!f[e[i].v]){ f[e[i].v]=1; int d=dfs(e[i].v); f[e[i].v]=0; if(!mx1){ mx1=d; } else if(!mx2){ mx2=d; if(mx2>mx1) swap(mx1,mx2); } else{ if(d>mx2) mx2=d; if(mx2>mx1) swap(mx1,mx2); } } } ans=max(ans,mx1+mx2+1); if(!mx1&&!mx2){ return 1; } return mx1+1; } int main(){ n=rd(); int x,y; for(int i=1;i<=n-1;i++){ x=rd(),y=rd(); e[i]=(E){x,y,g[x]};g[x]=i; e[i+n-1]=(E){y,x,g[y]};g[y]=i+n-1; } f[1]=1; dfs(1); printf("%d\n",ans-1); return 0; }
|