您的位置:首页 > 其它

The Accomodation of Students 二分图判定+匹配

2017-12-19 19:53 162 查看
模板题,复习一下模板

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 205;
int n, m, tot, head[maxn], vis[maxn], match[maxn];
struct Edge { int to, next; } edges[maxn*maxn];
void init() { tot = 0; memset(head, -1, sizeof(head)); }
void addedge(int u, int v) {
edges[++tot].to = v; edges[tot].next = head[u]; head[u] = tot;
}
bool dfs(int u) {
for (int i = head[u]; ~i; i = edges[i].next) {
int v = edges[i].to;
if (vis[v]) {
if (vis[v] == -vis[u]) continue;
else return false;
}
else {
vis[v] = -vis[u];
if (!dfs(v)) return false;
}
}
return true;
}

bool solve(int u) {
vis[u] = 1;
for (int i = head[u]; ~i; i = edges[i].next) {
int v = edges[i].to, w = match[v];
if (w < 0 || !vis[w] && solve(w)) {
match[u] = v;
match[v] = u;
return true;
}
}
return false;
}

int maxflow() {
int ans = 0;
memset(match, -1, sizeof(match));
for (int i = 1; i <= n; i++) {
if (match[i] < 0) {
memset(vis, 0, sizeof(vis));
if (solve(i)) ans++;
}

}
return ans;
}

int main() {
int u, v;
while (~scanf("%d %d", &n, &m)) {
init();
for (int i = 1; i <= m; i++) {
scanf("%d %d", &u, &v);
addedge(u, v); addedge(v, u);
}
memset(vis, 0, sizeof(vis));
bool ok = true;
for (int i = 1; i <= n; i++) {
if (vis[i]) continue;
vis[i] = 1;
if (!dfs(i)) { ok = false; break; }
}
if (!ok) printf("No\n");
else printf("%d\n", maxflow());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐