pjudge#21614-[PR #1]守卫【Kruskal生成树,费用流】

正题

题目链接:http://pjudge.ac/problem/21614


题目大意

给出一张\(n\)个点\(m\)条边的一张图,有\(k\)个守卫,每个守卫都有一个点集\(S\)表示这个守卫可以被派遣到这个点集中的某个点,然后你可以选择一些边删除,要求使得每个点都恰好和一个守卫联通,要求留下的边的权值和最小。

\(1\leq n\leq 300,1\leq m\leq \frac{n\times (n-1)}{2}\)


解题思路

首先最后的所有边肯定都是最小生成树上的边,我们可以先把最小生成树求出来。

然后我们考虑把最后有守卫的点集\(S\)拿出来建一棵虚树,那么假设存在一条边\(x\leftrightarrow y\),那么原树\(x,y\)肯定不连通,也就是\(x\leftrightarrow y\)路径上肯定有一条边会被删除。

显然我们删除路径上权值最大的边是最优的,嗯考虑到这个最大的边,我们可以建一个Kruskal生成树来更好的考虑。

那么对于一个边化成的点,这条边如果产生贡献,当且仅当它的两棵子树中都有点有守卫。

考虑使用费用流解决这个问题,对于一个产生贡献的点,如果左右两边都有流量上来它就会产生贡献,并且会继承一个流量上去,否则如果有一个流量就直接继承上去。

那么建法就很简单了,对于这个点\(x\)建立\(x\rightarrow t\)流量\(1\),费用\(w\)\(x\rightarrow fa_x\)流量\(1\),费用\(0\)

并且对于每个根,我们都建立\(x\rightarrow t\)流量\(1\),费用\(inf\),并且在最后减去这些\(inf\)即可。这样我们求一个最大费用最大流就是对的了。因为Kruskal生成树的原因,深度越小的节点权值肯定越大,所以两个流量肯定会在它们的\(LCA\)处产生贡献(因为只能流一个上去)。


code

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define ll long long
using namespace std;
const ll N=1500,inf=1e18;
struct node{
	ll x,y,w;
}e[N*N];
struct edge{
	ll to,next,w,c;
}a[N*20];
ll n,m,k,s,t,tot,ans,cnt,wr,fa[N];
ll ls[N],f[N],mf[N],pre[N];
bool v[N];queue<int> q;
bool cmp(node x,node y)
{return x.w<y.w;}
ll find(ll x)
{return (fa[x]==x)?x:(fa[x]=find(fa[x]));}
void addl(ll x,ll y,ll w,ll c){
	a[++tot].to=y;a[tot].next=ls[x];ls[x]=tot;a[tot].w=w;a[tot].c=c;
	a[++tot].to=x;a[tot].next=ls[y];ls[y]=tot;a[tot].w=0;a[tot].c=-c;
	return;
}
bool SPFA(){
	memset(f,0xcf,sizeof(f));
	q.push(s);f[s]=0;v[s]=1;mf[s]=inf;
	while(!q.empty()){
		ll x=q.front();q.pop();v[x]=0;
		for(ll i=ls[x];i;i=a[i].next){
			ll y=a[i].to;
			if(a[i].w&&f[x]+a[i].c>f[y]){
				f[y]=f[x]+a[i].c;pre[y]=i;
				mf[y]=min(mf[x],a[i].w);
				if(!v[y])q.push(y),v[y]=1;
			}
		}
	}
	return f[t]>-inf;
}
void Update(){
	ans+=mf[t]*f[t];
	ll x=t;wr+=mf[t];
	while(x!=s){
		a[pre[x]].w-=mf[t];
		a[pre[x]^1].w+=mf[t];
		x=a[pre[x]^1].to;
	}
	return;
}
signed main()
{
	scanf("%lld%lld%lld",&n,&m,&k);
	s=n*2+k+1;t=s+1;tot=1;
	for(ll i=1;i<=m;i++)
		scanf("%lld%lld%lld",&e[i].x,&e[i].y,&e[i].w);
	for(ll i=1;i<=n;i++)fa[i]=i;
	sort(e+1,e+1+m,cmp);cnt=n;
	ll sum=0;
	for(ll i=1;i<=m;i++){
		ll x=find(e[i].x),y=find(e[i].y);
		if(x==y)continue;
		fa[x]=fa[y]=++cnt;fa[cnt]=cnt;
		addl(x,cnt,1,0);addl(y,cnt,1,0);
		addl(cnt,t,1,e[i].w);sum+=e[i].w;
	}
	for(ll i=1;i<=cnt;i++)
		if(fa[i]==i)addl(i,t,1,1e9),sum+=1e9;
	for(ll i=1,r;i<=k;i++){
		scanf("%lld",&r);++cnt;
		addl(s,cnt,1,0);
		for(ll j=1,x;j<=r;j++)
			scanf("%lld",&x),addl(cnt,x,1,0);
	}
	while(SPFA())Update();sum-=ans;
	if(sum>=1e9||wr<k)return puts("-1")&0;
	printf("%lld\n",sum);
	return 0;
}
posted @ 2022-04-24 16:34  QuantAsk  阅读(20)  评论(0编辑  收藏  举报