题解:CF875F Royal Questions
并查集模拟费用流。
考虑费用流建模,一个公主连边
将公主按照
不难发现增广路一定形如
这个性质之所以是对的是因为一组匹配
考虑使用并查集维护一个点可以走到的唯一一个能走向汇点的点即可做到
#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;
}