(网络流24题大多需要spj,所以需要一个有spj的oj,本系列代码均在www.oj.swust.edu.cn测试通过)
这道题的模型很显然,源点向每个试卷连接一条容量为1的边,每个试卷向对应的类型连接一条容量为一的边,每个类型向汇点连接一条容量为需要数量的边,跑一边最大流即可。
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<ctime>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define INF 100000000
struct bian
{
int l,r,f,lei;
}a[1000000];
int d[100000];
int s=0,t=99999;
int fir[1000000];
int nex[1000000];
bool bfs()
{
static int dui[1000000];
memset(d,-1,sizeof(d));
int top=1,my_final=2;
dui[top]=s;
d[s]=1;
while(top<my_final)
{
int u=dui[top++];
for(int o=fir[u];o;o=nex[o])
{
if(a[o].f && d[a[o].r]==-1)
{
dui[my_final++]=a[o].r;
d[a[o].r]=d[u]+1;
if(a[o].r==t) return true;
}
}
}
return false;
}
int dinic(int u,int flow)
{
if(u==t) return flow;
int left=flow;
for(int o=fir[u];o&&left;o=nex[o])
{
if(a[o].f && d[a[o].r]==d[u]+1)
{
int temp=dinic(a[o].r,min(a[o].f,left));
if(!temp) d[a[o].r]=-1;
left-=temp;
a[o].f-=temp;
a[o^1].f+=temp;
}
}
return flow-left;
}
int tot=1;
void add_edge(int l,int r,int f,int lei=0)
{
a[++tot].l=l;
a[tot].r=r;
a[tot].f=f;
a[tot].lei=lei;
nex[tot]=fir[l];
fir[l]=tot;
}
int trueans[25][2000];
int top[25];
int main()
{
int k,n;
scanf("%d%d",&k,&n);
int zong=0;
for(int i=1;i<=k;i++)
{
int x;
scanf("%d",&x);
zong+=x;
add_edge(i,t,x);
add_edge(t,i,0);
}
for(int i=1;i<=n;i++)
{
add_edge(s,i+k,1);
add_edge(i+k,s,0);
int m;
scanf("%d",&m);
for(int j=1;j<=m;j++)
{
int x;
scanf("%d",&x);
add_edge(i+k,x,1,1);
add_edge(x,i+k,0);
}
}
int ans=0;
while(bfs()) ans+=dinic(s,INF);
if(ans!=zong)
{
cout<<"No Solution!";
return 0;
}
else
{
for(int i=2;i<=tot;i++)
if(a[i].f==0 && a[i].lei)
trueans[a[i].r][++top[a[i].r]]=a[i].l-k;
for(int i=1;i<=k;i++)
{
cout<<i<<": ";
for(int j=1;j<=top[i];j++) printf("%d ",trueans[i][j]);
printf("\n");
}
}
return 0;
}