【poj1985】 Cow Marathon

时间:2023-03-09 18:54:18
【poj1985】 Cow Marathon

http://poj.org/problem?id=1985 (题目链接)

题意

  求树上两点间最长距离。题目背景以及输入描述请见poj1984

Solution

  树的直径。

代码

// poj1985
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#define LL long long
#define MOD 100000000
#define inf 2147483640
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std; const int maxn=40010;
struct edge {int to,next,w;}e[maxn<<1];
int n,m,rt,ans,cnt,head[maxn]; void link(int u,int v,int w) {
e[++cnt].to=v;e[cnt].next=head[u];head[u]=cnt;e[cnt].w=w;
e[++cnt].to=u;e[cnt].next=head[v];head[v]=cnt;e[cnt].w=w;
}
void dfs(int x,int fa,int d) {
if (ans<d) ans=d,rt=x;
for (int i=head[x];i;i=e[i].next)
if (e[i].to!=fa) dfs(e[i].to,x,d+e[i].w);
}
int main() {
scanf("%d%d",&n,&m);
char ch;
for (int u,v,w,i=1;i<=m;i++) {
scanf("%d%d%d %c",&u,&v,&w,&ch);
link(u,v,w);
}
rt=ans=0;dfs(1,0,0);
dfs(rt,0,0);
printf("%d",ans);
return 0;
}