Pseudoforest (伪森林) 最大生成树

时间:2021-09-30 12:40:05

Pseudoforest

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 402 Accepted Submission(s): 173
 
Problem DescriptionIn 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.

 
InputThe 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.
 
OutputOutput 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 <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define MAX_V 10005
using namespace std;

int V, E, K;
int flag, n;
int u, v, w;
int ans;
struct edge {
int u, v, w;
};

edge es[MAX_V << 4];
bool circle[MAX_V];
int pa[MAX_V];
int high[MAX_V];

bool cmp(const edge &e1, const edge &e2) {
return e1.w > e2.w;
}

void init(int n) {
for (int i = 0; i <= n; i++) {
pa[i] = i;
high[i] = 0;
}
}

int _find(int x) {
if (pa[x] == x) return pa[x];
else return pa[x] = _find(pa[x]);
}

int same(int x, int y) {
return _find(x) == _find(y);
}

void unite(int x, int y, int w) {
x = _find(x);
y = _find(y);
if (x == y) {
// 如果两个点都不在环内,加上这条边,形成环,将两个点标记在环内
if (!circle[x]) {
ans += w;
circle[x]= 1;
}
return ;
}
// 都不在环中
if (!circle[x] && !circle[y]) {
ans += w;

if (high[x] < high[y]) {
pa[x] = y;
} else {
pa[y] = x;
if (high[x] == high[y]) high[x]++;
}
} else if (!circle[x] || !circle[y]) {
// 有一个在环中
circle[x] = circle[y] = 1;
ans += w;

if (high[x] < high[y]) {
pa[x] = y;
} else {
pa[y] = x;
if (high[x] == high[y]) high[x]++;
}

}
}

int main(void)
{
// freopen("in.txt", "r", stdin);
while (~scanf("%d%d", &V, &E)) {
if (V == 0 && E == 0) break;
memset(circle, 0, sizeof(circle));
for (int i = 0; i < E; i++) {
scanf("%d%d%d", &es[i].u, &es[i].v, &es[i].w);
}
ans = 0;
sort(es, es + E, cmp);
init(V); // 初始化并查集
for (int i = 0; i < E; i++) {
edge e = es[i];
unite(e.u, e.v, e.w);
}
printf("%d\n", ans);
}
return 0;
}