并查集模拟费用流。
考虑费用流建模,一个公主连边 ,再连边 ,每个王子连边 。
将公主按照 从大到小加入后,图上没有正环,只用考虑增广路即可。
不难发现增广路一定形如 ,其中 是因为之前走了一条 形成的反悔边,注意力集中一下,你发现一个点要么可以直接走向汇点,要么可以通过不断走反悔边和普通边走到唯一一个可以走到汇点的点,要么不断走反悔边和普通边会陷入循环,没有增广路。
这个性质之所以是对的是因为一组匹配 产生的影响是之前不断走反悔边和普通边走到 的点现在会通过 走到 上,而假若 之前就会走到 上就会形成一个环,一旦走入这个环就不会有任何增广路,因此这个环可以直接视作删去。
考虑使用并查集维护一个点可以走到的唯一一个能走向汇点的点即可做到 。
#include<bits/stdc++.h>
using namespace std;
//#define int long long
//#define lowbit(x) (x&(-x))
//#define bp push_back
//#define sz size
//#define cl clear
const int maxn = 2e5+114;
pair<int,pair<int,int> > a[maxn];
int n,m;
int ans;
int ch[maxn];//使用的点走退流边到的点 走不到有流量的点就是 0 自己有流量就是自己
int found(int u){
return ch[u]=(ch[u]==u?u:found(ch[u]));
}
bool cmp(pair<int,pair<int,int> > x,pair<int,pair<int,int> > y){
return x>y;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++) ch[i]=i;
for(int i=1;i<=m;i++) cin>>a[i].second.first>>a[i].second.second>>a[i].first;
sort(a+1,a+m+1,cmp);
for(int i=1;i<=m;i++){
int u=a[i].second.first,v=a[i].second.second,w=a[i].first;
if(found(u)!=0){
ans+=w;
if(found(v)==found(u)) ch[found(u)]=0;
else ch[found(u)]=found(v);
}else if(found(v)!=0){
ans+=w;
if(found(v)==found(u)) ch[found(v)]=0;
else ch[found(v)]=found(u);
}
}
cout<<ans<<'\n';
return 0;
}