hdu 4514

http://acm.hdu.edu.cn/showproblem.php?pid=4514

题意:先判断给定的图中是否有环,没有则对森林进行求最长路。

思路:dfs判断是否有环,然后对每棵树,两次dfs求最长路,最后取最大的。

View Code
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#pragma comment(linker, "/STACK:36777216")//开大点栈
using namespace std;

const int maxn = 100005;

struct nd{
    int v,w,next;
}as[maxn*20];

int cnt,ok,ans,xx;
int vis[maxn],hp[maxn],fa[maxn];

void add(int u,int v,int w)
{
    as[cnt].v = v;
    as[cnt].w = w;
    as[cnt].next = hp[u];
    hp[u] = cnt++;
}

void dfs(int pre,int cur,int sum,int f)
{
    int chong = 0;
    if(sum>ans){
        xx = cur;
        ans = sum;
    }
    if(ok)return;

    fa[cur] = f;
    vis[cur] = 1;
    for(int i = hp[cur]; i ^ -1; i = as[i].next){
        int to = as[i].v;
        if(to==pre && !chong){chong=1;continue;}
        if(vis[to])ok = 1;
        dfs(cur,to,sum+as[i].w,f);
    }
    vis[cur] = 0;
}

int max(int x,int y){return x>y?x:y;}

int main()
{
    int i,u,v,n,m,w;
    while(scanf("%d%d",&n,&m)==2)
    {
        for(i = 0; i <= n; ++ i){
            hp[i] = -1;
            vis[i] = 0;
            fa[i] = 0;
        }
        cnt = 0;

        for(i = 0; i < m; ++ i)
        {
            scanf("%d %d %d",&u,&v,&w);
            add(u,v,w);
            add(v,u,w);
        }

        ok = 0;
        for(i = 1; i <= n && !ok; ++ i)if(!fa[i])
            dfs(-1,i,0,1);
        for(i = 0; i <= n; ++ i)fa[i]=0;
        if(ok)puts("YES");
        else{
            int out = 0;
            for(i = 1; i <= n; ++ i)if(!fa[i]){
                ans = 0;
                dfs(-1,i,0,i);
                dfs(-1,xx,0,i);
                out = max(out,ans);
            }
            printf("%d\n",out);
        }

    }
    return 0;
}

 

posted on 2013-03-23 10:57  aigoruan  阅读(220)  评论(0)    收藏  举报

导航