本文主要是介绍P3386 【模板】二分图最大匹配(匈牙利算法,网络流),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
匈牙利
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;const int maxn = 1e3 + 7;
vector<int>G[maxn];
int match[maxn],vis[maxn];
int n,m,e;
void add(int x,int y) {G[x].push_back(y);G[y].push_back(x);
}
int dfs(int u) {for(int i = 0;i < G[u].size();i++) {int v = G[u][i];if(!vis[v]) {vis[v] = 1;if(!match[v] || dfs(match[v])) {match[v] = u;return 1;}}}return 0;
}
int query() {int sum = 0;for(int i = 1;i <= n;i++) {memset(vis,0,sizeof(vis));if(dfs(i)) sum++;}return sum;
}
int main() {scanf("%d%d%d",&n,&m,&e);for(int i = 1;i <= e;i++) {int x,y;scanf("%d%d",&x,&y);add(x,y + n);}n += m;printf("%d\n",query() / 2);return 0;
}
最大流
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
#include<queue>
#include <map>using namespace std;
typedef long long ll;
const int inf = 1 << 29, N = 50010, M = 300010;
int head[N], ver[M], edge[M], Next[M], d[N];
int n, m, s, t, tot;
ll maxflow;
queue<int> q;void add(int x, int y, int z) {ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;ver[++tot] = x, edge[tot] = 0, Next[tot] = head[y], head[y] = tot;
}bool bfs() { // 在残量网络上构造分层图memset(d, 0, sizeof(d));while (q.size()) q.pop();q.push(s); d[s] = 1;while (q.size()) {int x = q.front(); q.pop();for (int i = head[x]; i; i = Next[i])if (edge[i] && !d[ver[i]]) {q.push(ver[i]);d[ver[i]] = d[x] + 1;if (ver[i] == t) return 1;}}return 0;
}int dinic(int x, int flow) { // 在当前分层图上增广if (x == t) return flow;int rest = flow, k;for (int i = head[x]; i && rest; i = Next[i])if (edge[i] && d[ver[i]] == d[x] + 1) {k = dinic(ver[i], min(rest, edge[i]));if (!k) d[ver[i]] = 0; // 剪枝,去掉增广完毕的点edge[i] -= k;edge[i ^ 1] += k;rest -= k;}return flow - rest;
}map<pair<int,int>,int>mp;int main() {int e;cin >> n >> m >> e;s = 0,t = n + m + 1;
// cin >> s >> t; // 源点、汇点mp.clear();tot = 1;for (int i = 1; i <= e; i++) {int x, y, c;scanf("%d%d", &x, &y);if(x > n || y > m) continue;if(mp[{x,y + n}]) continue;mp[{x,y + n}] = 1;add(x, y + n, 1);}for(int i = 1;i <= n;i++) add(s,i,1);for(int i = n + 1;i <= n + m;i++) add(i,t,1);int flow = 0;while (bfs())while (flow = dinic(s, inf)) maxflow += flow;cout << maxflow << endl;
}
这篇关于P3386 【模板】二分图最大匹配(匈牙利算法,网络流)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!