码迷,mamicode.com
首页 > 其他好文 > 详细

【poj1985】 Cow Marathon

时间:2016-10-06 00:21:12      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

  

【poj1985】 Cow Marathon

标签:

原文地址:http://www.cnblogs.com/MashiroSky/p/5933122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!