HDU 3367 最大生成树

Pseudoforest

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1276    Accepted Submission(s): 482


Problem Description
In graph theory, a pseudoforest is an undirected graph in which every connected component has at most one cycle. The maximal pseudoforests of G are the pseudoforest subgraphs of G that are not contained within any larger pseudoforest of G. A pesudoforest is larger than another if and only if the total value of the edges is greater than another one’s.

 

Input
The input consists of multiple test cases. The first line of each test case contains two integers, n(0 < n <= 10000), m(0 <= m <= 100000), which are the number of the vertexes and the number of the edges. The next m lines, each line consists of three integers, u, v, c, which means there is an edge with value c (0 < c <= 10000) between u and v. You can assume that there are no loop and no multiple edges.
The last test case is followed by a line containing two zeros, which means the end of the input.
 

Output
Output the sum of the value of the edges of the maximum pesudoforest.
 

Sample Input
3 3 0 1 1 1 2 1 2 0 1 4 5 0 1 1 1 2 1 2 3 1 3 0 1 0 2 2 0 0
 

Sample Output
3 5

 

由于题目要求,每个连通分量最多出现一个环,按权值从大到小排序,所以用并查集判断时,标记一个集合里面是否出现过环,假设两个不同的集合里都有环,则不能合并,否则可以合并,假设在同一个集合里且没出现过环,则把环标记出来。

代码:

 

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<string>
using namespace std;
int fa[20000],vis[20000];
int find(int x)
{
        if(fa[x]!=x)fa[x]=find(fa[x]);
        return fa[x];
}
struct node
{
        int from,to,len;
}edge[300000];
bool cmp(node a,node b)
{
        return a.len>b.len;
}
int main()
{
        int i,j,k,m,n,p,q;
        while(~scanf("%d%d",&n,&m))
        {
                if(n==0&&m==0)break;
                for(i=0;i<n;i++)fa[i]=i;
                memset(vis,0,sizeof(vis));
                for(i=0;i<m;i++)scanf("%d%d%d",&edge[i].from,&edge[i].to,&edge[i].len);
                sort(edge,edge+m,cmp);
                __int64 ans=0;
                for(i=0;i<m;i++)
                {
                        p=find(edge[i].from);
                        q=find(edge[i].to);
                        if(p!=q)
                        {
                                if(vis[p]&&vis[q])continue;
                                if(vis[p]||vis[q])vis[p]=vis[q]=1;
                                ans+=edge[i].len;
                                fa[p]=q;
                        }
                        else
                        {
                                if(!vis[p])
                                {
                                        ans+=edge[i].len;
                                        vis[p]=1;
                                }
                        }
                }
                printf("%I64d\n",ans);
        }
        return 0;
}

 

posted @ 2013-09-13 16:39  线性无关  阅读(127)  评论(0)    收藏  举报