版权声明:那个,最起码帮我加点人气吧,署个名总行吧 https://blog.csdn.net/qq_41670466/article/details/82722235
题目链接:https://cn.vjudge.net/problem/HDU-3367
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.
题意就是在给定的图里面找到一个边权值的和最大的一个子图,这个子图要满足只有一个环的要求;
思路:可以看出它本质上是要去求边权值和最大的子图,那么就以为着整体上是利用克鲁斯卡尔算法得到的最大生成树,然后在次基础上进行一些改变,就是要得到子图上只有一个环,那么就可以想到,因为利用kru算法来实现子图 的过程中边是按照边权less的顺序给出,那么就意味着前一条边和后一条边可能不属于同一个树,于是就要先对在不在一个树分析,如果在一个树里面,那么如果想要这条边连成后不会出现两个环,只能是两个端点都不能在环中。再对两个端点不在一个树上进行分析,要想这两个端点连成后只有一个环,那么只有一下几种情况:两个端点都不在环里面,其中一个在环里面。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e5+10;
const int maxm=1e4+10;
struct Edge
{
int from,val,to;
}edge[maxn];
int pre[maxm];
int cir[maxn];//用来判定是不是在一个环里面
int n,m;
int find(int x)
{
if(pre[x]==x)
return x;
return pre[x]=find(pre[x]);
}
bool cmp(Edge a,Edge b)
{
return a.val>b.val;
}
long long solve()
{
long long ans=0;
sort(edge+1,edge+1+m,cmp);
for(int i=1;i<=m;i++)
{
int fx=find(edge[i].from),fy=find(edge[i].to);
if(fx==fy)
{
if(!cir[fx]&&!cir[fy])
{
ans+=edge[i].val;
cir[fx]=cir[fy]=1;
}
}
else
{
if(!cir[fx]&&!cir[fy])
{
ans+=edge[i].val;
pre[fx]=fy;
}
else if(!cir[fx]||!cir[fy])
{
ans+=edge[i].val;
pre[fx]=fy;
cir[fx]=cir[fy]=1;
}
}
}
return ans;
}
void ini()
{
memset(cir,0,sizeof(cir));
for(int i=0;i<=n;i++)
pre[i]=i;
}
int main()
{
while(scanf("%d %d",&n,&m)&&(n||m))
{
ini();
for(int i=1;i<=m;i++)
scanf("%d %d %d",&edge[i].from,&edge[i].to,&edge[i].val);
long long ans=solve();
cout<<ans<<endl;
}
return 0;
}