题目地址:https://www.nowcoder.com/acm/contest/136/C
dfs找出最长路和次长路,将两个结果相加再加上起点即可;
1 #include<iostream> 2 using namespace std; 3 4 const int N = 1e6+5; 5 struct EDGE { 6 int to, pre; 7 }edge[2*N]; 8 int n, tot=1, head[N], first[N], second[N], ans=0; 9 10 void read(int &x) { 11 int f = 1; x = 0; 12 char ch = getchar(); 13 14 while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();} 15 while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();} 16 x *= f; 17 } 18 19 void add_edge(int a, int b) 20 { 21 edge[tot].to = b; 22 edge[tot].pre = head[a]; 23 head[a] = tot++; 24 } 25 26 void dfs(int k, int pre) 27 { 28 for(int i=head[k]; i; i=edge[i].pre) { 29 int to = edge[i].to; 30 if(to == pre) continue; 31 32 dfs(to, k); 33 if(first[k] < first[to]+1) { 34 second[k] = first[k]; 35 first[k] = first[to]+1; 36 } 37 else 38 second[k] = max(second[k], first[to]+1); 39 } 40 ans = max(ans, first[k]+second[k]); 41 } 42 43 int main() 44 { 45 read(n); 46 for(int a,b,i=1; i<n; i++) { 47 read(a); read(b); 48 add_edge(a,b); 49 add_edge(b,a); 50 } 51 52 dfs(1, 0); 53 cout<<ans+1<<endl; 54 55 return 0; 56 }