0%

HDU 3367 Pseudoforest 最大生成树

Pseudoforest

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)

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

题意

给出一张图,求最大生成树。要求每一个连通块上只能有一个环。

分析

对于Kruskal来说,最小/最大生成树只是改变一下排序顺序即可。这里需要另外注意添加的就是对环的判断了:

如果两个节点不在同一棵树内,且分别不成环,则可合并;

如果两个节点在同一棵树内,但是未成环,则加上这条边之后将成环;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;

typedef struct nod
{
int x,y,c;
} node;
node a[100010];

bool op(node a,node b)
{
return a.c>b.c;
}

int father[10010];
bool flag[10010];

void clean_father(int n)
{
for (int i=0;i<n;i++) father[i]=i;
}

int getfather(int x)
{
if (father[x]!=x) father[x]=getfather(father[x]);
return father[x];
}

void link(int x,int y)
{
father[getfather(x)]=getfather(y);
}

int main()
{
int n,m;
while (scanf("%d%d",&n,&m))
{
if (n==0&&m==0) break;

for (int i=1;i<=m;i++) scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].c);
sort(&a[1],&a[m+1],op);

clean_father(n);
memset(flag,0,sizeof(flag));
int ans=0;
for (int i=1;i<=m;i++)
if (getfather(a[i].x)!=getfather(a[i].y))
{
if (!(flag[getfather(a[i].x)]&&flag[getfather(a[i].y)]))
{

if (flag[getfather(a[i].x)]||flag[getfather(a[i].y)])
{
flag[getfather(a[i].x)]=true;
flag[getfather(a[i].y)]=true;
}
link(a[i].x,a[i].y);
ans+=a[i].c;
}
} else
if (!flag[getfather(a[i].x)])
{
ans+=a[i].c;
flag[getfather(a[i].x)]=true;
}

printf("%d\n",ans);
}

return 0;
}