您的位置:首页 > 其它

hdu 3367 Pseudoforest (伪森林) not 最大生成树 解题报告

2016-06-07 21:48 736 查看
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<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 10000+100;
struct node
{
int x, y, v;
bool operator < (const node &s) const
{
return v>s.v;
}
}w[maxn * 10];

int n, m, sum, f[maxn], circle[maxn];

int find(int x)
{
return x == f[x] ? x : (f[x] = find(f[x]));
}
void merge(int x,int y,int v)
{
x = find(x);
y = find(y);
if(x == y)
{
//如果两个点都不在环内,加上这条边,形成环,将两个点标记在环内
if(!circle[x] && !circle[y])
{
circle[x] = circle[y] = 1;
sum += v;
}
return;
}
else
{
//都不在环内
if(!circle[x] && !circle[y])
{
sum += v;
f[x] = y;
}
//有一个在环内
else if(!circle[x] || !circle[y])
{
sum += v;
f[x] = y;
circle[x] = circle[y] = 1;
}
}
}

int main()
{
while(scanf("%d%d", &n, &m) != EOF && n || m)
{
sum = 0;
memset(circle, 0, sizeof(circle));
for(int i = 0; i <= 10000; i++)
f[i] = i;
for(int i = 0; i < m; i++)
scanf("%d%d%d", &w[i].x, &w[i].y, &w[i].v);
sort(w, w+m);
for(int i = 0; i < m; i++)
{
merge(w[i].x, w[i].y, w[i].v);
}
printf("%d\n", sum);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm 伪森林 并查集