正题
题目链接:http://www.51nod.com/Challenge/Problem.html#problemId=1551
题目大意
nnn个集合,nnn个物品,每个集合有一些物品,一个价钱。满足任意kkk个集合都有kkk种不同的物品。
要求一个最低的价格来购买集合且购买集合数等于里面不同物品数。
解题思路
这个条件根据hallhallhall定理可以证明如果一个集合对应一个物品则可以找到完全匹配。
那么也就是对于每个集合可以对应一个唯一的物品,每个一个物品也可以对应一个唯一的集合。
那么如果一个集合中有其他的物品,那么这个其他的物品所对应的集合也要选择,这样就可以用最大权闭合图来解决这个问题。
codecodecode
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N=1210,inf=2147483647;
queue<int> q;
struct node{int to,next,w;
};
int n,ans,d[N];
struct New_Flow{node a[N*200];int s,t,tot=1,ls[N],dep[N];void addl(int x,int y,int w){a[++tot].to=y;a[tot].next=ls[x];ls[x]=tot;a[tot].w=w;a[++tot].to=x;a[tot].next=ls[y];ls[y]=tot;a[tot].w=0;return;}bool bfs(){while(!q.empty())q.pop();q.push(s);memset(dep,0,sizeof(dep));dep[s]=1;while(!q.empty()){int x=q.front();q.pop();for(int i=ls[x];i;i=a[i].next){int y=a[i].to;if(dep[y]||!a[i].w)continue;dep[y]=dep[x]+1;if(y==t)return 1;q.push(y);}}return 0;}int dinic(int x,int flow){if(x==t)return flow;int rest=0,k;for(int i=ls[x];i;i=a[i].next){int y=a[i].to;if(dep[x]+1!=dep[y]||!a[i].w)continue;rest+=(k=dinic(y,min(a[i].w,flow-rest)));a[i].w-=k;a[i^1].w+=k;if(rest==flow)return flow;}if(!rest)dep[x]=0;return rest;}int net_flow(){int ans=0;while(bfs())ans+=dinic(s,inf);return ans;}
}p,nf;
int main()
{scanf("%d",&n);p.s=2*n+1;p.t=p.s+1;for(int i=1;i<=n;i++){int k,x;scanf("%d",&k);p.addl(p.s,i,1);for(int j=1;j<=k;j++)scanf("%d",&x),p.addl(i,x+n,1);p.addl(i+n,p.t,1);}p.net_flow();for(int x=1;x<=n;x++)for(int i=p.ls[x];i;i=p.a[i].next){int y=p.a[i].to;if(!p.a[i].w&&y>n&&y<=2*n){d[y-n]=x;break;}}for(int x=1;x<=n;x++){for(int i=p.ls[x];i;i=p.a[i].next){int y=p.a[i].to;if(p.a[i].w&&y>n&&y<=2*n)nf.addl(x,d[y-n],inf);}}nf.s=n+1;nf.t=n+2;for(int i=1;i<=n;i++){int x;scanf("%d",&x);x=-x;if(x<0)nf.addl(i,nf.t,-x);else nf.addl(nf.s,i,x),ans+=x;}printf("%d\n",nf.net_flow()-ans);return 0;
}