洛谷 P3386 【模板】二分图最大匹配

传送门

#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using p = pair<int, int>;
const double pi(acos(-1));
const int inf(0x3f3f3f3f);
const int mod(1e9 + 7);
const int maxn(1e3 + 10);
const int maxm(1e5 + 10);
int ecnt, head[maxn];
bool vis[maxn];
int match[maxn];

struct edge {
    int to, nxt;
} edges[maxm];

template<typename T = int>
inline const T read()
{
    T x = 0, f = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = (x << 3) + (x << 1) + ch - '0';
        ch = getchar();
    }
    return x * f;
}

template<typename T>
inline void write(T x, bool ln)
{
    if (x < 0) {
        putchar('-');
        x = -x;
    }
    if (x > 9) write(x / 10, false);
    putchar(x % 10 + '0');
    if (ln) putchar(10);
}

void addEdge(int u, int v)
{
    edges[ecnt].to = v;
    edges[ecnt].nxt = head[u];
    head[u] = ecnt++;
}

bool dfs(int u)
{
    for (int i = head[u]; compl i; i = edges[i].nxt) {
        int v = edges[i].to;
        if (not vis[v]) {
            vis[v] = true;
            if (not match[v] or dfs(match[v])) {
                match[v] = u;
                return true;
            }
        }
    }
    return false;
}

int hungary(int n)
{
    int res = 0;
    for (int i = 1; i <= n; ++i) {
        memset(vis, false, sizeof vis);
        res += dfs(i);
    }
    return res;
}

int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("input.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);
    memset(head, -1, sizeof head);
    int n = read(), m = read(), e = read();
    while (e--) {
        int u = read(), v = read() + n;
        addEdge(u, v);
        addEdge(v, u);
    }
    write(hungary(n), true);
    return 0;
}
原文地址:https://www.cnblogs.com/singularity2u/p/13934055.html