题目描述
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.
输入格式
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 the sum of the value of the edges of the maximum pesudoforest.
输入样例
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输出样例
3
5
分析
题目大意是给出n个点和m条边的无向图,求这个图的最大伪森林,即可以在森林的基础上加边使之存在环,但一个连通分量内最多只有一个环。
对于这道题,我们按照Kruskal算法思想对边进行从大到小排序,然后依次判断最先得到的必然是最大伪森林,这点是和求最大最小生成树的思想是相似的,而对于伪森林来讲,主要有以下四种情况需要讨论,以点a、b举例:
- 两点不连通:
1.点a和b不连通,且各自都处在有环的连通分量内。
2.点a和b不连通,且至少有一方不在有环的连通分量内。 - 两点连通:
1.点a和b连通,且连通分量内存在环。
2.点a和b连通,且连通分量内不存在环。
即以下四张图:
综上,对于以上四种情况,我们在Kruskal思想下,对于并查集中的根,如果他在环中我们就标记他,对于已经标记存在环的点我们不能进行建边,以下是源代码。
源程序
#include <bits/stdc++.h>
#define MAXN 10005
using namespace std;
struct Edge{
int u,v,w;
bool operator <(const Edge a)const{
return w>a.w;
}
}edge[MAXN*10];
int n,m,father[MAXN];
bool vis[MAXN];
int find(int x)
{
if(x==father[x])return x;
return father[x]=find(father[x]);
}
int main()
{
while(scanf("%d%d",&n,&m)&&(n+m)){
for(int i=0;i<n;i++) //初始化
father[i]=i,vis[i]=false;
for(int i=1;i<=m;i++)
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w);
sort(edge+1,edge+m+1);
int ans=0; //累积权重
for(int i=1;i<=m;i++){
int u=edge[i].u,v=edge[i].v,w=edge[i].w;
int fu=find(u),fv=find(v);
if(fu!=fv){ //两点不连通
if(vis[fu]&&vis[fv]) //都存在环
continue;
else{ //至少一方不存在环
ans+=w;
father[fu]=fv;
vis[fv]=vis[fv]|vis[fu]; //保持该连通分量内是否存在环
}
}
else{ //两点连通
if(vis[fu]) //该连通分量内存在环
continue;
else{
ans+=w;
vis[fu]=vis[fv]=true; //标记存在环
}
}
}
printf("%d\n",ans);
}
}