模板
题目链接:https://www.luogu.org/problemnew/show/P3386
这篇博文写的很好:http://blog.csdn.net/dark_scope/article/details/8880547
我能不能放上链接就走人(逃
Codes:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N = 1000 + 5;
int n,m,e;
int head[N],nxt[N * N],cnt,ans,link[N];//N^2数组千万别忘了啊啊啊!!!
bool vis[N];
struct Edge{
int ff,tt;
}edge[N * N];//N^2空间啊啊啊!!!
void build(int f,int t){
edge[++ cnt] = (Edge){f,t};
nxt[cnt] = head[f];
head[f] = cnt;
return;
}
bool dfs(int x){
for(int i = head[x];i;i = nxt[i]){
int t = edge[i].tt;
if(!vis[t]){
vis[t] = 1;
if(!link[t] || dfs(link[t])){
link[t] = x;
return true;
}
}
}
return false;
}
void init(){
for(int i = 1;i <= m;i ++)
vis[i] = 0;
return;
}
int main(){
scanf("%d%d%d",&n,&m,&e);
int a,b;
for(int i = 1;i <= e;i ++){
scanf("%d%d",&a,&b);
if(a > n || b > m) continue;//洛谷竟然卡这里……
build(a,b);
}
for(int i = 1;i <= n;i ++){
init();
if(dfs(i)) ans ++;
}
cout << ans << '
';return 0;
}
匹配:
Codes:
bool dfs(int x){ //x为左边
for(int i = head[x];i;i = nxt[i]){
int t = edge[i].tt;//t为右边
if(vis[t]) continue;//标记过
vis[t] = 1;
if (!link[t] || dfs(link[t])){
//还没被连起来或者能腾出个位置来,这里使用递归
link[t]=x;
return true;
}
}
return false;
}
MAS:
空间注意开N^2。