poj1985 树直径
题意:求树的直径
思路:板子题(没错这篇博客就是存板子的)
AC代码:
#include "stdio.h" #include "string.h" struct Edge{ int to,w,next; }; Edge e[200005]; int head[200005],vis[200005]; int cnt,s,t,p,d[200005]; // d数组存储路径 void add(int u, int v, int w){ e[cnt].to=v; e[cnt].w=w; e[cnt].next=head[u]; head[u]=cnt++; } void Dfs(int u, int sum){ vis[u]=1; if(sum>p){ p=sum; s=u; } for(int i=head[u]; i!=-1; i=e[i].next){ int v=e[i].to; if(!vis[v]) Dfs(v,sum+e[i].w); } } void Dfs1(int u, int fa, int sum){ vis[u]=1; d[u]=fa; if(sum>=p){ p=sum; t=u; } for(int i=head[u]; i!=-1; i=e[i].next){ int v=e[i].to; if(!vis[v]) Dfs1(v,u,sum+e[i].w); } } int main(){ int n,m,a,b,c; char cc; memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); scanf("%d%d",&n,&m); getchar(); for(int i=1; i<=m; ++i){ scanf("%d%d%d %c",&a,&b,&c,&cc); add(a,b,c); add(b,a,c); } Dfs(1,0); memset(vis,0,sizeof(vis)); Dfs1(s,0,0); //printf("%d ",t); //for(int i=d[t]; i!=0; i=d[i]) printf("%d ",i); printf("%d\n",p); return 0; }