给出一棵树,求出树中的最长连。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 #define maxn 40005 6 struct{ 7 int y,c,next; 8 }ee[maxn<<1]; 9 int link[maxn],t,root1,k; 10 void insert(int a,int b,int c) 11 { 12 ee[++t].y=b; 13 ee[t].c=c; 14 ee[t].next=link[a]; 15 link[a]=t; 16 } 17 void dfs(int root,int father,int num) 18 { 19 int flag=0; 20 for(int i=link[root];i;i=ee[i].next) 21 if(ee[i].y!=father){ 22 flag=1; 23 dfs(ee[i].y,root,num+ee[i].c); 24 } 25 if(!flag&&k<num){ 26 k=num; 27 root1=root; 28 } 29 } 30 int main() 31 { 32 int n,m; 33 while(~scanf("%d%d",&n,&m)){ 34 t=0; 35 memset(link,0,sizeof(link)); 36 while(m--){ 37 int a,b,c; 38 char s[5]; 39 scanf("%d%d%d%s",&a,&b,&c,s); 40 insert(a,b,c); 41 insert(b,a,c); 42 } 43 k=0; 44 dfs(1,1,0); 45 k=0; 46 dfs(root1,root1,0); 47 printf("%d\n",k); 48 } 49 return 0; 50 }