Pseudoforest

来源:互联网 发布:星光大道网络赛区鲁婷 编辑:程序博客网 时间:2024/06/10 14:58

Pseudoforest

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

Total Submission(s): 254    Accepted Submission(s): 112

 
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 30 1 11 2 12 0 14 50 1 11 2 12 3 13 0 10 2 20 0
Sample Output
35
 
森林,允许多个连通分支。
 
#include<cstdio>#include<algorithm>#include<cstring>using namespace std;const int MAXN = 10000 + 10;const int MAXM = 100000 + 10;int u[MAXM], v[MAXM], w[MAXM], r[MAXM];int p[MAXN],  fh[MAXN];  //fh表示以i为父节点的连通分支是否有环 int cmp(int i, int j){return w[i] > w[j];}int find_set(int i){if(i != p[i]) p[i] = find_set(p[i]);return p[i];}void union_set(int i, int j){int x = find_set(i);int y = find_set(j);p[y] = x;}int main(){int n, m;int a, b, c;while(scanf("%d%d", &n, &m) && (n != 0 || m!= 0)){memset(fh, 0, sizeof(fh));for(int i = 0; i < m; i++){scanf("%d%d%d", &a, &b, &c);u[i] = a;v[i] = b;w[i] = c;}for(int i = 0; i < n; i++) p[i] = i;for(int i = 0; i < m; i++){r[i] = i;}sort(r, r+m, cmp);int cnt = 0;for(int i = 0; i < m; i++){int e = r[i];int x = find_set(u[e]);int y = find_set(v[e]);if(x != y){//不同连通分支 if(!fh[x] || !fh[y]){if(fh[x]) union_set(x, y);else union_set(y, x);cnt += w[e];}}else {  //同一个连通分支 if(fh[x])  //已有环continue;else {cnt += w[e];fh[x] = 1;} }}printf("%d\n", cnt);}return 1;}

0 0
原创粉丝点击