*HDU3367 最小生成树

Pseudoforest

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


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
 

 

Source
 
题意:
给出n个点和m条边,问最大生成树并且此生成树中有且只有一个环。
代码:
 1 //排序后每枚举一条边时判断两端点所在的集合中有没有环,如果不在一个集合中:都有环不能合并,否则可以合并。
 2 //在一个集合中:都没有环,把这条边上就有环了。记住更新loop.
 3 #include<iostream>
 4 #include<cstdio>
 5 #include<cstring>
 6 #include<algorithm>
 7 using namespace std;
 8 int fat[10004],loop[10004];//loop 标记有没有环。
 9 struct Lu
10 {
11     int u,v,w;
12 };
13 bool cmp(Lu x,Lu y)
14 {
15     return x.w>y.w;
16 }
17 int find(int x)
18 {
19     if(fat[x]!=x)
20     fat[x]=find(fat[x]);
21     return fat[x];
22 }
23 int main()
24 {
25     int n,m;
26     while(scanf("%d%d",&n,&m)&&(n+m))
27     {
28         for(int i=0;i<n;i++)
29         fat[i]=i;
30         memset(loop,0,sizeof(loop));
31         Lu L[100005];
32         int sum=0;
33         for(int i=0;i<m;i++)
34         {
35             scanf("%d%d%d",&L[i].u,&L[i].v,&L[i].w);
36         }
37         sort(L,L+m,cmp);
38         for(int i=0;i<m;i++)
39         {
40             int x=find(L[i].u),y=find(L[i].v);
41             if(x!=y)
42             {
43                 if(!loop[x]||!loop[y])
44                 {
45                     sum+=L[i].w;
46                     fat[y]=x;
47                     loop[x]=loop[x]|loop[y];
48                 }
49             }
50             else if(!loop[x])
51             {
52                 sum+=L[i].w;
53                 loop[x]=1;
54             }
55         }
56         printf("%d\n",sum);
57     }
58     return 0;
59 }

 

posted @ 2016-11-10 09:24  luckilzy  阅读(372)  评论(0编辑  收藏  举报