二分图多重匹配
二分图多重匹配
用网络流求解即可,左边的点和右边的点之间容量仍然为1,但是源点与左边的点容量为左边的点能够选取次数,右边的点与汇点之间同理,跑最大流即可。
构造方案时,仍然看每条边的流量,判断是否匹配。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<sstream>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<deque>
#include<cstdlib>
#include<ctime>
#define dd double
#define ld long double
#define ll long long
#define ull unsigned long long
#define N 800
#define M 80000
using namespace std;
const int INF=0x3f3f3f3f;
inline int Min(int a,int b){
return a>b?b:a;
}
inline int read(){
int x=0,f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
struct edge{
int to,next,f;
inline void intt(int to_,int ne_,int f_){
to=to_;next=ne_;f=f_;
}
};
edge li[M];
int head[N],tail=1,now[N];
inline void add(int from,int to,int f){
li[++tail].intt(to,head[from],f);
head[from]=tail;
}
int m,n,s,t,ans,allr;
queue<int> q;
int d[N];
inline bool bfs(int s){
// printf("ENTER\n");
while(q.size()) q.pop();
memset(d,0,sizeof(d));
d[s]=1;now[s]=head[s];q.push(s);
while(q.size()){
int top=q.front();q.pop();
for(int x=head[top];x;x=li[x].next){
int to=li[x].to,f=li[x].f;
if(!f||d[to]) continue;
d[to]=d[top]+1;now[to]=head[to];
q.push(to);
if(to==t) return 1;
}
}
if(!d[t]) return 0;
return 1;
}
inline int dicnic(int k,int flow){
if(k==t) return flow;
int rest=flow,x;
for(x=now[k];x&&rest;x=li[x].next){
int to=li[x].to,re=li[x].f;
if(!re||d[to]!=d[k]+1) continue;
int val=dicnic(to,Min(rest,re));
if(!val) d[to]=0;
li[x].f-=val;
li[x^1].f+=val;
rest-=val;
}
now[k]=x;
return flow-rest;
}
int main(){
m=read();n=read();s=m+n+1;t=m+n+2;
for(int i=1;i<=m;i++){
int r=read();allr+=r;
add(s,i,r);add(i,s,0);
}
for(int i=m+1;i<=m+n;i++){
int c=read();
add(i,t,c);add(t,i,0);
}
for(int i=1;i<=m;i++)
for(int j=m+1;j<=m+n;j++)
add(i,j,1),add(j,i,0);
int flow=0;
// printf("here\n");
while(bfs(s))
while(flow=dicnic(s,INF)) ans+=flow;
if(allr!=ans){
printf("0\n");
return 0;
}
printf("1\n");
for(int i=1;i<=m;i++){
for(int x=head[i];x;x=li[x].next){
int to=li[x].to,f=li[x].f;
if(to==s||f) continue;
printf("%d ",to-m);
}
printf("\n");
}
return 0;
}