Codeforces 120F Spiders

看了chenxing老湿的代码,我真心为自己智商捉鸡啊。。一遍dfs搞定啊。。

 1 #include <cstdio>
 2 #include <cstring>
 3 #define maxn 110
 4 int first[maxn],v[maxn*2],next[maxn*2];
 5 int len,e;
 6 inline int max(int a,int b){
 7     return a > b ? a : b;
 8 }
 9 
10 void init(){
11     e = 0;
12     memset(first,-1,sizeof(first));
13 }
14 
15 void add_edge(int a,int b){
16     v[e] = b;
17     next[e] = first[a];
18     first[a] = e++;
19 }
20 
21 int dfs(int u,int fa){
22     int ret = 0,maxdep;
23     for(int i = first[u];i != -1;i = next[i]){
24         if(v[i] == fa)  continue;
25         maxdep = dfs(v[i],u);
26         len = max(len,ret + maxdep + 1);
27         ret = max(ret,maxdep + 1);
28     }
29     return ret;
30 }
31 
32 int main(){
33     freopen("input.txt", "r", stdin);
34     freopen("output.txt", "w", stdout);
35     int n,m;
36     while(scanf("%d",&n) != EOF){
37         int ans = 0;
38         while(n--){
39             scanf("%d",&m);
40             init();
41             len = 0;
42             for(int i = 0;i < m-1;i++){
43                 int a,b;
44                 scanf("%d%d",&a,&b);
45                 add_edge(a,b);
46                 add_edge(b,a);
47             }
48             dfs(1,-1);
49             ans += len;
50         }
51         printf("%d
",ans);
52     }
53 }
View Code
原文地址:https://www.cnblogs.com/zhexipinnong/p/3238761.html