您的位置:首页 > 其它

poj 1985 Cow Marathon 树的直径

2017-04-18 19:00 316 查看
题意:

求树的直径

分析:

dfs2次即可

ACcode

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#define maxn 150005
#define inf 0x3f3f3f3f
#include <cstring>
#define ll long long
using namespace std;
struct N{
int to,next,w;
}my[maxn];
int head[maxn],tot,ans,ed;
int dp[maxn];
void init(){
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
tot=0;
}
void add(int u,int v,int w){
my[tot].to=v;my[tot].next=head[u];
my[tot].w=w;head[u]=tot++;
}
void dfs(int st,int w){
dp[st]=1;
if(ans<w)ans=w,ed=st;
for(int i=head[st];i!=-1;i=my[i].next){
int v=my[i].to;
if(!dp[v])dfs(v,w+my[i].w);
}
}
int main(){
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){
init();
int a,b,c;
char s[2];
for(int i=1;i<=m;++i){
scanf("%d%d%d%s",&a,&b,&c,s);
add(a,b,c);
add(b,a,c);
}
ans=0;
dfs(1,0);
memset(dp,0,sizeof(dp));
dfs(ed,0);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: