二分图匹配
附上两种方法:
网络流
据说所有的二分图题目都可以用网络流跑过去,可能还快一些
话不多说,只有代码
/*
二分图匹配的题大多可用网络流做
此处为Dinic模板,详见网络流模板
*/
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<ctime>
#include<queue>
#include<stack>
#include<vector>
#define rg register
#define il inline
#define lst long long
#define ldb long double
#define N 2050
#define E 2000050
using namespace std;
const int Inf=1e9;
il int read()
{
rg int s=0,m=0;rg char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')m=1;ch=getchar();}
while(ch>='0'&&ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return m?-s:s;
}
int n,m,e;
int hd[N],cnt=1;
int dep[N];
queue<int> Q;
struct EDGE{int to,nxt,c,fb;}ljl[E<<1];
il void add(rg int p,rg int q,rg int o)
{
ljl[cnt]=(EDGE){q,hd[p],o,cnt+1},hd[p]=cnt++;
ljl[cnt]=(EDGE){p,hd[q],0,cnt-1},hd[q]=cnt++;
}
il bool BFS()
{
for(rg int i=1;i<=n+m+2;++i)dep[i]=0;
while(!Q.empty())Q.pop();
Q.push(1),dep[1]=1;
while(!Q.empty())
{
rg int now=Q.front();Q.pop();
for(rg int i=hd[now];i;i=ljl[i].nxt)
{
rg int qw=ljl[i].to;
if(ljl[i].c&&(!dep[qw]))
{
dep[qw]=dep[now]+1;
Q.push(qw);
}
}
}
return dep[m+n+2];
}
int dfs(rg int now,rg int aim,rg int flow)
{
if(now==aim||(!flow))return flow;
rg int res=0;
for(rg int i=hd[now];i;i=ljl[i].nxt)
{
rg int qw=ljl[i].to;
if(ljl[i].c&&dep[qw]==dep[now]+1)
{
rg int kk=dfs(qw,aim,min(ljl[i].c,flow));
res+=kk,flow-=kk;
ljl[i].c-=kk,ljl[ljl[i].fb].c+=kk;
}
}
return res;
}
il int Dinic()
{
rg int ans=0;
while(BFS())
ans+=dfs(1,n+m+2,Inf);
return ans;
}
int main()
{
n=read(),m=read(),e=read();
for(rg int i=1;i<=n;++i)
add(1,i+1,1);
for(rg int i=1;i<=m;++i)
add(i+n+1,m+n+2,1);
for(rg int i=1;i<=e;++i)
{
rg int p=read()+1,q=read()+n+1;
if(p<=n+1&&q<=m+n+1)add(p,q,1);
}
printf("%d
",Dinic());
return 0;
}
匈牙利算法
不会自行百度
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<ctime>
#include<queue>
#include<stack>
#include<vector>
#define rg register
#define il inline
#define lst long long
#define ldb long double
#define N 2050
#define E 2000050
using namespace std;
const int Inf=1e9;
il int read()
{
rg int s=0,m=0;rg char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')m=1;ch=getchar();}
while(ch>='0'&&ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return m?-s:s;
}
int n,m,e,ans;
int hd[N],cnt;
int match[N],vis[N];
struct EDGE{int to,nxt;}ljl[E<<1];
il void add(rg int p,rg int q){ljl[++cnt]=(EDGE){q,hd[p]},hd[p]=cnt;}
bool dfs(rg int now)
{
for(rg int i=hd[now];i;i=ljl[i].nxt)
{
rg int qw=ljl[i].to;
if(!vis[qw])
{
vis[qw]=1;
if(!match[qw]||dfs(match[qw]))
{
match[qw]=now;return 1;
}
}
}
return 0;
}
int main()
{
n=read(),m=read(),e=read();
for(rg int i=1;i<=e;++i)
{
rg int p=read(),q=read();
if(p<=n&&q<=m)add(p,q+n);
}
for(rg int i=1;i<=n;++i)
{
memset(vis,0,sizeof(vis));
if(dfs(i))ans++;
}
printf("%d
",ans);
return 0;
}