hdu 3367 Pseudoforest

Posted SDAU_ZG

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 3367 Pseudoforest相关的知识,希望对你有一定的参考价值。

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
 
题意:
 给出一个图,要求出最大的pseudoforest, 所谓pseudoforest就是指这个图的一个子图,这个子图的每个连通分量中最多只能有一个环, 而且这个子图的所有权值之和最大。这个就是所谓的伪森林。
参考思路:

1.两个端点属于同一个集合。如果这个集合还没有环,那么就加上这条边并标记次集合有环


2.两个端点属于不同的集合。如果这两个集合至多只有一个集合有环的话,那么就可以加上这条边合并这两个集合,一定记得要修改合并后集合的环标志。



代码:

#include <iostream>
#include<stdio.h>
#include<algorithm>
#define maxn 100010
using namespace std;
int n,m;
typedef struct edge
{
int u,v,w;
} Edge;
Edge e[maxn];
int fa[maxn];
int loop[maxn];
int cmp(const void *a,const void *b)
{
  Edge* aa = (Edge*)a;
  Edge* bb = (Edge*)b;
  return bb->w - aa->w;
}


int MyFind(int a)
{
  return fa[a] == a?a:fa[a] = MyFind(fa[a]);
}


int main()
{
  while(true)
  {
    scanf("%d %d",&n,&m);
    if(n+m == 0) break;
    for(int i = 0; i < n; i++)
    {
      fa[i] = i;
      loop[i] = 0;
    }
    for(int i = 0; i < m; i++)
    {
      scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w);
    }
    qsort(e,m,sizeof (Edge),cmp);
    int ans = 0;
    for(int i = 0 ; i < m; i++)
    {
      int u = e[i].u;
      int v = e[i].v;
      int w = e[i].w;
      int fa_u = MyFind(u);
      int fa_v = MyFind(v);
      if(fa_u == fa_v )
      {
        if(!loop[fa_u])
        {
          loop[fa_u] = 1;
          ans+=w;
        }
      }
      else
      {
        if(loop[fa_u] + loop[fa_v] < 2) //两个连通分量至多一个环
        {
          fa[fa_v] = fa_u;
          loop[fa_u] += loop[fa_v]; //改变环标记,父节点的环标记为两个集合的环数目的和
          ans+=w;
        }
      }
    }
    printf("%d\n",ans);
  }
  return 0;
}

 

以上是关于hdu 3367 Pseudoforest的主要内容,如果未能解决你的问题,请参考以下文章

hdu3367Pseudoforest(伪森林)

hdu 3367 Pseudoforest 最大生成树★

[HDOJ3367]Pseudoforest(并查集,贪心)

Pseudoforest(伪最大生成树)

洛谷P3367

并查集模板并查集模板 luogu-3367