解题报告 P3254 圆桌问题
紫钦
·
·
个人记录
题目链接:P3254 圆桌问题。
题目大意
数据规模:$1\leqslant n\leqslant150\ ,\ 1\leqslant m\leqslant270$ 。
# 解法:二分图多重匹配
不知道拿二分图匹配该怎么做,反正用网络流做还是蛮直观的。
+ 源点 $s$ 向所有的 $n$ 个点连边,容量为该点的匹配上限。
+ 所有的 $m$ 个点向汇点 $t$ 连边,容量为该点的匹配上限。
+ 所有的 $n$ 个点向所有的 $m$ 个点连边。
跑最大流,判断最大流是否等于所有的 $n$ 个点匹配上限之和即可。
至于输出匹配方案,只需遍历这 $n\times m$ 条边,满流即为匹配。
# 注意事项
+ 我使用 $ISAP$ 求最大流,时间复杂度为 $O((n+m)^2nm)$ 。
# $AC$ 代码
[评测记录](https://www.luogu.com.cn/record/30415104)。
```cpp
#include<cstdio>
#include<cstring>
#include<queue>
namespace Qza{
#define MAXN 425
#define MAXM 82000
#define INF 2147483647
int h[MAXN],gap[MAXN],pre[MAXN],cur[MAXN];
int en[MAXN],to[MAXM],nex[MAXM],w[MAXM];
void add_edge(int x,int y,int v)
{
static int cnt=-1;
nex[++cnt]=en[x]; to[cnt]=y; en[x]=cnt; w[cnt]=v;
nex[++cnt]=en[y]; to[cnt]=x; en[y]=cnt; w[cnt]=0;
}
void bfs(int s,int t)
{
register int u,v;
std::queue<int> q;
for(h[t]=0,q.push(t);!q.empty();) {
u=q.front(); q.pop();
for(int p=en[u];p!=-1;p=nex[p])
if(w[p^1] && !h[v=to[p]] && v!=t)
h[v]=h[u]+1,q.push(v);
}
}
int add_flow(int s,int t)
{
register int flow=INF,u,p;
u=t; while(u!=s) p=pre[u],flow=std::min(flow,w[p]),u=to[p^1];
u=t; while(u!=s) p=pre[u],w[p]-=flow,w[p^1]+=flow ,u=to[p^1];
return flow;
}
int ISAP(int s,int t,int n)
{
if(s==t) return INF;
register int u=s,v,flow=0,minhv;
register bool found;
bfs(s,t);
if(!h[s]) return 0;
for(int i=1;i<=n;++i) {
cur[i]=en[i];
if(h[i]) ++gap[h[i]];
else if(i!=t) h[i]=n;
}
while(h[s]<n) {
if(u==t) flow+=add_flow(s,t),u=s;
found=false;
for(int &p=cur[u];p!=-1;p=nex[p])
if(w[p] && h[v=to[p]]<h[u]) {
found=true; u=v; pre[v]=p;
break;
}
if(!found) {
if(!(--gap[h[u]])) break;
minhv=n;
for(int p=en[u];p!=-1;p=nex[p])
if(w[p]) minhv=std::min(minhv,h[to[p]]);
h[u]=minhv+1;
++gap[h[u]];
cur[u]=en[u];
if(u!=s) u=to[pre[u]^1];
}
}
return flow;
}
int read()
{
char ch=getchar();int x=0;
while(ch<'0' || ch>'9') ch=getchar();
while(ch>='0'&&ch<='9') x=(x*10)+(ch^48),ch=getchar();
return x;
}
void main()
{
memset(en,0xff,sizeof(en));
int n,m,s,t,maxflow,peo=0;
n=read(); m=read();
s=n+m+1; t=s+1;
for(register int i=1,val;i<=n;++i) add_edge(s,i,(val=read())),peo+=val;
for(register int i=1;i<=m;++i) add_edge(i+n,t,read());
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j)
add_edge(i,j+n,1);
maxflow=ISAP(s,t,t);
if(peo==maxflow) {
printf("1\n");
for(register int i=1;i<=n;++i) {
for(register int p=en[i];p!=-1;p=nex[p])
if(!w[p] && to[p]!=s) printf("%d ",to[p]-n);
putchar('\n');
}
}
else printf("0");
return ;
}
}
int main()
{
Qza::main();
return 0;
}
```