poj 1985 Cow Marathon 树的直径

来源:互联网 发布:服装店记账软件 编辑:程序博客网 时间:2024/06/06 03:19

题意:

求树的直径

分析:

dfs2次即可

ACcode

#include <iostream>#include <cstdio>#include <algorithm>#include <cmath>#include <cstring>#define maxn 150005#define inf 0x3f3f3f3f#include <cstring>#define ll long longusing 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;}


0 0
原创粉丝点击