P2763 试题库问题 最大流
题意: 给出n道题目,每道题目可以属于很多个类型,现在出题需要每个类型有指定数量的题目,给出匹配方案
分析: 这道题目其实建图比较简单,但是由于这题还让给出最大流的一个匹配方案,需要对数组实现的邻接表很熟悉,是我太菜了
做法:
最左边一个超级源点,标号为0
连往n道题目,题目标号为
[
1
,
n
]
[1,n]
[1,n],边容量为1
题目连往各自所属的类型,边容量为1,类型标号为
[
n
+
1
,
n
+
k
+
1
]
[n+1,n+k+1]
[n+1,n+k+1]
类型连往最右边的超级源点,标号为n+k+2,容量为各自指定的数量
Dinic和SAP都可,由于没写过dinic就试着写一下
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<queue>
#include<map>
#define ll long long
#define pb push_back
#define rep(x,a,b) for (int x=a;x<=b;x++)
#define repp(x,a,b) for (int x=a;x<b;x++)
#define W(x) printf("%d\n",x)
#define WW(x) printf("%lld\n",x)
#define pi 3.14159265358979323846
#define mem(a,x) memset(a,x,sizeof a)
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
using namespace std;
const int maxn=2e4+7;
const int INF=1e9;
const ll INFF=1e18;
struct node
{
int to,next,cap,flow;
}edge[maxn];
int tol,k,n,x,q;
int head[maxn];
void init()
{
int tol=0;
mem(head,-1);
}
void add(int u,int v,int w,int rw=0)
{
edge[tol].to=v;edge[tol].cap=w;edge[tol].flow=0;
edge[tol].next=head[u];head[u]=tol++;
edge[tol].to=u;edge[tol].cap=rw;edge[tol].flow=0;
edge[tol].next=head[v];head[v]=tol++;
}
int Q[maxn];
int dep[maxn],cur[maxn],sta[maxn];
bool bfs(int sx,int ex,int n)
{
int front=0,tail=0;
mem(dep,-1);
dep[sx]=0;
Q[tail++]=sx;
while(front<tail)
{
int u=Q[front++];
for (int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if (edge[i].cap>edge[i].flow&&dep[v]==-1)
{
dep[v]=dep[u]+1;
if (v==ex)return true;
Q[tail++]=v;
}
}
}
return false;
}
int dinic(int sx,int ex,int n)
{
int maxflow=0;
while(bfs(sx,ex,n))
{
repp(i,0,n)cur[i]=head[i];
int u=sx,tail=0;
while(cur[sx]!=-1)
{
if (u==ex)
{
int tp=INF;
for (int i=tail-1;i>=0;i--)tp=min(tp,edge[sta[i]].cap-edge[sta[i]].flow);
maxflow+=tp;
for (int i=tail-1;i>=0;i--)
{
edge[sta[i]].flow+=tp;
edge[sta[i]^1].flow-=tp;
if (edge[sta[i]].cap-edge[sta[i]].flow==0)tail=i;
u=edge[sta[tail]^1].to;
}
}
else if (cur[u]!=-1&&edge[cur[u]].cap>edge[cur[u]].flow&&dep[u]+1==dep[edge[cur[u]].to])
{
sta[tail++]=cur[u];
u=edge[cur[u]].to;
}
else
{
while(u!=sx&&cur[u]==-1)u=edge[sta[--tail]^1].to;
cur[u]=edge[cur[u]].next;
}
}
}
return maxflow;
}
int main()
{
init();
int sum=0;
scanf("%d%d",&k,&n);
rep(i,1,k)
{
scanf("%d",&x);sum+=x;
add(n+i,n+k+1,x,0);
}
rep(i,1,n)
{
scanf("%d",&q);
rep(j,1,q)
{
scanf("%d",&x);
add(i,n+x,1,0);
}
add(0,i,1,0);
}
if (dinic(0,n+k+1,n+k+2)==sum)
{
vector<int> V[30];
for (int i=0;i<tol;i+=2)
{
if (edge[i].to>=n+1&&edge[i].to<=n+k+1)
if (edge[i^1].to>=1&&edge[i^1].to<=n)
if (edge[i].flow!=0)
V[edge[i].to-n].pb(edge[i^1].to);
}
rep(i,1,k)
{
printf("%d:",i);
repp(j,0,V[i].size())
printf(" %d",V[i][j]);
printf("\n");
}
}
else
printf("No Solution!\n");
}