21天零基础入门ACM
21天零基础入门ACM之 第18天
匈牙利算法
匈牙利算法
匈牙利算法是用来解决二分图最大匹配的算法。
在学习匈牙利算法之前,一定要知道二分图的概念。
其实匈牙利算法就是一个不断寻找增广路径的问题。
例题:
例题1:
https://ac.nowcoder.com/acm/problem/20472
代码:
#include <bits/stdc++.h>
using namespace std;
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
typedef long long ll; typedef unsigned long long ull; typedef long double ld;
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; }
ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
const int mod=1e9+7;
const int N=1e5+7;
int n;
int edge[205][205]; //存入边的信息
bool vis[205]; //是否访问
int link[205]; //于之配对的x的值
bool dfs(int x){
for(int i=1;i<=n;i++){
if(!vis[i]&&edge[x][i]){
vis[i]=1;
if(!link[i]||dfs(link[i])){
link[i]=x;
return true;
}
}
}
return false;
}
int main(){
int T;
cin>>T;
while(T--){
cin>>n;
memset(link,0,sizeof(link));
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>edge[i][j];
}
}
bool flag=true;
for(int i=1;i<=n;i++){
memset(vis,0,sizeof(vis));
if(!dfs(i)){
flag=false;break;
}
}
if(flag) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}
例题2:
http://acm.hdu.edu.cn/showproblem.php?pid=2063
#include <bits/stdc++.h>
using namespace std;
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
typedef long long ll; typedef unsigned long long ull; typedef long double ld;
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar()) s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; }
ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; }
ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
const int mod=1e9+7;
const int N=1e3+7;
int a,n,m,x,y;
int edge[N][N];
int link[N];
int vis[N];
bool dfs(int x){
for(int i=1;i<=m;i++){
if(edge[x][i]&&!vis[i]){
vis[i]=1;
if(!link[i]||dfs(link[i])){
link[i]=x;
return true;
}
}
}
return false;
}
int main(){
while(cin>>a&&a){
cin>>n>>m;
memset(edge,0,sizeof(edge));
memset(link,0,sizeof(link));
while(a--){
cin>>x>>y;
edge[x][y]=1;
}
int sum=0;
for(int i=1;i<=n;i++){
memset(vis,0,sizeof(vis));
if(dfs(i)) sum++;
}
cout<<sum<<endl;
//for(int i=1;i<=n;i++) cout<<link[i]<<endl;
}
return 0;
}