https://loj.ac/problem/6004
二分图多重匹配
#include <iostream> #include <stdio.h> #include <queue> #include <cstring> using namespace std; const int maxn = 1000; int head[maxn]; int tot = 0; struct edge{ int v,nex,w; }e[maxn*120]; void addedge(int u,int v,int w){ e[tot] = (edge){v,head[u],w}; head[u] = tot++; e[tot] = (edge){u,head[v],0}; head[v] = tot++; } int deep[maxn]; bool bfs(int S,int T){ memset(deep,0,sizeof(deep)); deep[S] = 1; queue<int> q; q.push(S); while(!q.empty()){ int now = q.front(); q.pop(); for(int i=head[now];i!=-1;i=e[i].nex){ int v = e[i].v; int w = e[i].w; if(deep[v]!=0 || w<=0) continue; deep[v] = deep[now]+1; q.push(v); } } return deep[T]; } int dfs(int now,int T,int maxflow){ if(now==T) return maxflow; int all = 0; for(int i=head[now];i!=-1 && all<maxflow;i=e[i].nex){ int v = e[i].v; int w = e[i].w; if(deep[v]!=deep[now]+1 || w<=0) continue; int tt = dfs(v,T,min(maxflow-all,w)); e[i].w-=tt; e[i^1].w+=tt; all+=tt; } return all; } int dinic(int S,int T){ int ret = 0; while(bfs(S,T)){ ret+=dfs(S,T,0x3f3f3f3f); } return ret; } int main() { int m,n; scanf("%d%d",&m,&n); memset(head,-1,sizeof(head)); int all = 0; for(int i=1;i<=m;i++){ int t ; scanf("%d",&t); all+=t; addedge(0,i,t); } for(int i=1;i<=n;i++){ int t; scanf("%d",&t); addedge(m+i,m+n+1,t); } for(int i=1;i<=m;i++){ for(int j=m+1;j<=m+n;j++){ addedge(i,j,1); } } int ans = dinic(0,m+n+1); if(all==ans){ printf("1\n"); for(int i=1;i<=m;i++){ for(int j=head[i];j!=-1;j=e[j].nex){ int v = e[j].v; int w = e[j].w; if(v<=m+n && v>=m+1 && w==0) { printf("%d ",v-m); } } printf("\n"); } }else{ printf("0\n"); } return 0; }