您的位置:首页 > 其它

POJ 1985 Cow Marathon(树的直径)

2016-02-12 14:49 393 查看
Description

给出一棵无向树,求树的直径

Input

第一行为两个整数n和m分别表示点数和边数,之后m行每行表示树的一条边

Output

输出树的直径长度

Sample Input

7 6

1 6 13 E

6 3 9 E

3 5 7 S

4 1 3 N

2 4 20 W

4 7 2 S

Sample Output

52

Solution

树的直径裸题

Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 111111
struct node
{
int to,c,next;
}edge[2*maxn];
int n,m,head[maxn],tot,dis[maxn],vis[maxn];
void init()
{
memset(head,-1,sizeof(head));
tot=0;
}
void add(int u,int v,int c)
{
edge[tot].to=v;
edge[tot].c=c;
edge[tot].next=head[u];
head[u]=tot++;
}
void dfs(int u)
{
for(int i=head[u];~i;i=edge[i].next)
{
int v=edge[i].to,c=edge[i].c;
if(!vis[v])
{
vis[v]=1;
dis[v]=dis[u]+c;
dfs(v);
}
}
}
int main()
{
int u,v,c,s;char op[3];
while(~scanf("%d%d",&n,&m))
{
init();
while(m--)
{
scanf("%d%d%d%s",&u,&v,&c,op);
add(u,v,c),add(v,u,c);
}
memset(vis,0,sizeof(vis));
dis[1]=0,vis[1]=1;
dfs(1);
for(int i=2,temp=-1;i<=n;i++)
if(dis[i]>temp)temp=dis[i],s=i;
memset(vis,0,sizeof(vis));
dis[s]=0,vis[s]=1;
dfs(s);
int ans=-1;
for(int i=1;i<=n;i++)
ans=max(ans,dis[i]);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: