湫湫系列故事——设计风景线

来源:互联网 发布:mac输入法切换设置 编辑:程序博客网 时间:2024/06/08 04:03

湫湫系列故事——设计风景线
Time Limit:3000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Submit

Status

Practice

HDU 4514
Description
  随着杭州西湖的知名度的进一步提升,园林规划专家湫湫希望设计出一条新的经典观光线路,根据老板马小腾的指示,新的风景线最好能建成环形,如果没有条件建成环形,那就建的越长越好。
  现在已经勘探确定了n个位置可以用来建设,在它们之间也勘探确定了m条可以设计的路线以及他们的长度。请问是否能够建成环形的风景线?如果不能,风景线最长能够达到多少?
  其中,可以兴建的路线均是双向的,他们之间的长度均大于0。
Input
  测试数据有多组,每组测试数据的第一行有两个数字n, m,其含义参见题目描述;
  接下去m行,每行3个数字u v w,分别代表这条线路的起点,终点和长度。

   [Technical Specification]
  1. n<=100000
  2. m <= 1000000
  3. 1<= u, v <= n
  4. w <= 1000
Output
  对于每组测试数据,如果能够建成环形(并不需要连接上去全部的风景点),那么输出YES,否则输出最长的长度,每组数据输出一行。
Sample Input
3 3
1 2 1
2 3 1
3 1 1


#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <vector>using namespace std;const int vmaxn=100010;struct Edge{    int to,w;    Edge(int a,int b)    {        to=a;        w=b;    }};int pre[vmaxn],dp[vmaxn],ans;vector<Edge> edge[vmaxn];int Find(int x){    int r=x;    while (pre[r]!=r)    {        r=pre[r];    }    int i=x,j;    while (pre[i]!=r)    {        j=pre[i];        pre[i]=r;        i=j;    }    return r;}void dfs(int u,int fa){    int maxx=0;    for (int i=0; i<edge[u].size(); i++)    {        int to=edge[u][i].to;        int w=edge[u][i].w;        if (to==fa)            continue;        dfs(to,u);        ans=max(ans,dp[to]+maxx+w);        maxx=max(maxx,dp[to]+w);    }    dp[u]=maxx;}int main(){    int n,m,a,b,c,i,j,tm;    while (scanf("%d%d",&n,&m)==2)    {        tm=m;        bool f=false;        for (i=1; i<=n; i++)        {            pre[i]=i;            dp[i]=-1;            edge[i].clear();        }        while (m--)        {            scanf("%d%d%d",&a,&b,&c);            if(f)                continue;            int fa=Find(a);                int fb=Find(b);                if (fa==fb)                {                    f=true;                    continue;                }                else                {                    pre[fb]=fa;                    edge[a].push_back(Edge(b,c));                    edge[b].push_back(Edge(a,c));                }        }        //while (m--){scanf("%d%d%d",&a,&b,&c);}        if (f)        {            printf("YES\n");        }        else        {            ans=0;            for (i=1; i<=n; i++)            {                if (dp[i]==-1)                    dfs(i,-1);            }            printf("%d\n",ans);        }    }    return 0;}
0 0
原创粉丝点击