题意
小N最近在研究NP完全问题,小O看小N研究得热火朝天,便给他出了一道这样的题目:
有n个球,用整数1到n编号。还有m个筐子,用整数1到m编号。
每个筐子最多能装3个球。
每个球只能放进特定的筐子中。具体有e个条件,第i个条件用两个整数vi和ui描述,表示编号为vi的球可以放进编号为ui的筐子中。
每个球都必须放进一个筐子中。如果一个筐子内有不超过1个球,那么我们称这样的筐子为半空的。
求半空的筐子最多有多少个,以及在最优方案中,每个球分别放在哪个筐子中。
小N看到题目后瞬间没了思路,站在旁边看热闹的小I嘿嘿一笑:“水题!”
然后三言两语道出了一个多项式算法。
小N瞬间就惊呆了,三秒钟后他回过神来一拍桌子:
“不对!这个问题显然是NP完全问题,你算法肯定有错!”
小I浅笑:“所以,等我领图灵奖吧!”
小O只会出题不会做题,所以找到了你——请你对这个问题进行探究,并写一个程序解决此题。
对于所有数据,T≤5,1≤n≤3m。保证 1≤vi≤n,1≤ui≤m,且不会出现重复的条件。保证至少有一种合法方案,使得每个球都放进了筐子,且每个筐子内球的个数不超过 3。M<=100
分析
我们可以把一个筐子拆成三个点,三个点之间两两连边,然后能放进这个筐子的球向这三个点分别连边。不难发现如果这个筐子是半空的,那么它自己就会贡献一个匹配。所以答案就是最大匹配-n。
剩下的就是套模板了。
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int N=605;
int n,m,k,f[N],cnt,last[N],tim,tic[N],pre[N],match[N],ty[N];
struct edge{int to,next;}e[500005];
queue<int> que;
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;
}
int point(int x,int y)
{
return (x-1)*3+y+n;
}
int find(int x)
{
if (f[x]==x) return x;
else return f[x]=find(f[x]);
}
void addedge(int u,int v)
{
e[++cnt].to=v;e[cnt].next=last[u];last[u]=cnt;
e[++cnt].to=u;e[cnt].next=last[v];last[v]=cnt;
}
int lca(int x,int y)
{
for (tim++;;swap(x,y))
if (x)
{
x=find(x);
if (tic[x]==tim) return x;
tic[x]=tim;x=pre[match[x]];
}
}
void shrink(int x,int y,int p)
{
while (find(x)!=p)
{
pre[x]=y;y=match[x];
if (ty[y]==2) ty[y]=1,que.push(y);
if (find(x)==x) f[x]=p;
if (find(y)==y) f[y]=p;
x=pre[y];
}
}
bool aug(int s)
{
for (int i=1;i<=n+m*3;i++) f[i]=i,ty[i]=pre[i]=0;
while (!que.empty()) que.pop();
que.push(s);ty[s]=1;
while (!que.empty())
{
int x=que.front();que.pop();
for (int i=last[x],y=e[i].to;i;i=e[i].next,y=e[i].to)
{
if (find(x)==find(y)||ty[y]==2) continue;
if (!ty[y])
{
ty[y]=2;pre[y]=x;
if (!match[y])
{
for (int tmp;x;y=tmp,x=pre[y]) tmp=match[x],match[x]=y,match[y]=x;
return 1;
}
else ty[match[y]]=1,que.push(match[y]);
}
else if (ty[y]==1)
{
int p=lca(x,y);
shrink(x,y,p);
shrink(y,x,p);
}
}
}
return 0;
}
int main()
{
int T=read();
while (T--)
{
n=read();m=read();k=read();
cnt=0;
memset(last,0,sizeof(last));
for (int i=1;i<=m;i++)
{
addedge(point(i,1),point(i,2));
addedge(point(i,2),point(i,3));
addedge(point(i,3),point(i,1));
}
for (int i=1;i<=k;i++)
{
int x=read(),y=read();
for (int j=1;j<=3;j++) addedge(x,point(y,j));
}
int ans=0;
memset(match,0,sizeof(match));
for (int i=1;i<=n+m*3;i++) if (!match[i]&&aug(i)) ans++;
printf("%d\n",ans-n);
//for (int i=1;i<=n;i++) printf("%d ",(match[i]-n-1)/3+1);
//puts("");
}
return 0;
}