我现在做的是第四专题编号为1008的试题,具体内容如下所示:
Problem H
Time Limit : 10000/5000ms (Java/Other) Memory Limit : 65536/65536K (Java/Other)
Total Submission(s) : 10 Accepted Submission(s) : 5
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.<br><br>
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.<br>The last test case is followed by a line containing two zeros, which means the end of the input.<br>
Output
Output the sum of the value of the edges of the maximum pesudoforest.<br>
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
简单题意:
给出一个图,求出最大的一个子图,要求这个子图的每个连通分量中最多只能有一个环,而且这个子图的所有权值之和最大。
解题思路:
求最大生成树很类似,但是有一点改变, 因为每个连通分量允许有一个回环, 所以,我们可以在进行合并两颗树时,要判断这两颗树是否有回环,如果两个树都有回环,那么明显不可以合并这两颗树, 如果只有一棵树有回环,那么可以合并,然后标上记号。如果两个都没有回环,那么就直接合并了。
如果有两个点是属于同一棵树上的,那么判断这棵树上是否已有回环,如果没有的话,那么允许有一个回环,可以链接这两点,再标上记号。
编写代码:
<span style="font-size:14px;">#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
typedef struct nn
{
int x,y,p;
}Node;
Node edg[100005];
int fath[10005],sum,cycle[10005];
int cmp(Node a,Node b)
{
return a.p>b.p;
}
void set_first(int n)
{
for(int i=0;i<n;i++)
{
fath[i]=i; cycle[i]=0;
}
}
int find_fath(int x)
{
if(x!=fath[x])
fath[x]=find_fath(fath[x]);
return fath[x];
}
void kruskal(int n,int m)
{
int a,b,k=0;
sum=0;
set_first(n);
sort(edg,edg+m,cmp);
for(int i=0;i<m;i++)
{
a=find_fath(edg[i].x);
b=find_fath(edg[i].y);
if(a!=b&&(cycle[a]!=1||cycle[b]!=1))
{
sum+=edg[i].p;
fath[a]=b;
if(cycle[a]) cycle[b]=cycle[a];
}
else if(cycle[a]==0)
{
sum+=edg[i].p; cycle[a]=1;
}
}
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)>0&&n+m!=0)
{
for(int i=0;i<m;i++)
scanf("%d%d%d",&edg[i].x,&edg[i].y,&edg[i].p);
kruskal(n,m);
printf("%d\n",sum);
}
}
</span>