家園重建

【簡要題意】有n個點和m條邊。選出其中的某些邊構成一個新的圖(不一定聯通),要求新圖中每個連通塊中至多有一個環。求新圖的邊權最大和。

【分析】貪心,依舊是一道kruskal類似的題,不同只是要記錄當前集合中是否有環。

【code】

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=310;
struct Edge{
	int u,v;
	int val;
}edge[maxn*maxn];
int f[maxn],flag[maxn];
int n,m;int ans;
inline void read(int &x){
	x=0;char tmp=getchar();int fl=1;
	while(tmp<'0'||tmp>'9'){if(tmp=='-') fl=-fl;tmp=getchar();}
	while(tmp>='0'&&tmp<='9') x=(x<<1)+(x<<3)+tmp-'0',tmp=getchar();
	x=x*fl;
}
bool cmp(Edge x,Edge y){return x.val>y.val;}
int find(int x){
	if(f[x]!=x) f[x]=find(f[x]);
	return f[x];
}
int main(){
	cin>>n>>m;
	for(int i=0;i<m;i++) read(edge[i].u),read(edge[i].v),read(edge[i].val);
	sort(edge,edge+m,cmp);
	for(int i=0;i<n;i++) f[i]=i;
	for(int i=0;i<m;i++){
		int x=find(edge[i].u),y=find(edge[i].v);
		if((x==y&&flag[x])||(x!=y&&flag[x]&&flag[y]))continue;
		if(x!=y) flag[y]=flag[x]||flag[y],f[x]=y;
		else flag[x]=1;	
		ans+=edge[i].val;
	}
	cout<<ans<<endl;
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章