luogu3386 【模板】二分图匹配 匈牙利算法 hdu2063 过山车 dinic

luogu

匈牙利算法

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int n, m, uu, vv, e, lnk[1005], ans;
bool a[1005][1005], vis[1005];
bool dfs(int u){
for(int i=1; i<=m; i++){
if(a[u][i] && !vis[i]){
vis[i] = true;
if(!lnk[i] || dfs(lnk[i])){
lnk[i] = u;
return true;
}
}
}
return false;
}
int main(){
cin>>n>>m>>e;
for(int i=1; i<=e; i++){
scanf("%d %d", &uu, &vv);
if(uu>n || vv>m) continue;
a[uu][vv] = true;
}
for(int i=1; i<=n; i++){
memset(vis, 0, sizeof(vis));
if(dfs(i)) ans++;
}
cout<<ans<<endl;
return 0;
}

hdu

建图最大流dinic

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
struct Edge{
int too, nxt, val;
}edge[4005];
int k, m, n, ss, tt, cnt, hea[1005], uu, vv, maxFlow, lev[1005];
const int oo=0x3f3f3f3f;
queue<int> d;
void add_edge(int fro, int too, int val){
edge[cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
hea[fro] = cnt++;
}
bool bfs(){
memset(lev, 0, sizeof(lev));
d.push(ss);
lev[ss] = 1;
while(!d.empty()){
int x=d.front();
d.pop();
for(int i=hea[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(!lev[t] && edge[i].val>0){
lev[t] = lev[x] + 1;
d.push(t);
}
}
}
return lev[tt]!=0;
}
int dfs(int x, int lim){
if(x==tt) return lim;
int addFlow=0;
for(int i=hea[x]; i!=-1 && addFlow<lim; i=edge[i].nxt){
int t=edge[i].too;
if(lev[t]==lev[x]+1 && edge[i].val>0){
int tmp=dfs(t, min(lim-addFlow, edge[i].val));
edge[i].val -= tmp;
edge[i^1].val += tmp;
addFlow += tmp;
}
}
return addFlow;
}
void dinic(){
while(bfs()) maxFlow += dfs(ss, oo);
}
int main(){
while(scanf("%d", &k)!=EOF){
if(!k) break;
scanf("%d %d", &m, &n);
ss = 0; tt = m + n + 1;
memset(hea, -1, sizeof(hea));
cnt = maxFlow = 0;
for(int i=1; i<=k; i++){
scanf("%d %d", &uu, &vv);
add_edge(uu, vv+m, 1);
add_edge(vv+m, uu, 0);
}
for(int i=1; i<=m; i++){
add_edge(ss, i, 1);
add_edge(i, ss, 0);
}
for(int i=m+1; i<=m+n; i++){
add_edge(i, tt, 1);
add_edge(tt, i, 0);
}
dinic();
printf("%d\n", maxFlow);
}
return 0;
}
上一篇:HDU 2063 过山车(二分匹配入门)


下一篇:hdu 2063 过山车 二分匹配(匈牙利算法)