大视野 1854 游戏 匈牙利算法

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1854

一道二分图匹配,用匈牙利就好,加点优化就不会 TLE 了
其他的分析可以看看类似的题目
比如:http://www.lydsy.com/JudgeOnline/problem.php?id=1191
以及题解:http://blog.csdn.net/sunsn343/article/details/69359855

本题代码

#include
#include
const int maxn = 1000500;
int head[maxn], line[maxn], f[maxn];
int n, m, tot, x, y;

struct Edge {
    int u, v, next;
    Edge(int u = 0, int v = 0, int next = -1) : u(u), v(v), next(next) {}
} e[maxn*2];

void add_edge(int u, int v) {
    e[++tot] = (Edge){u, v, head[u]};
    head[u] = tot;
}

bool dfs(int u, int t) {
    for(int i = head[u]; i != -1; i = e[i].next) {
        int v = e[i].v;
        if(f[v] == t) continue;
        f[v] = t;
        if(!line[v] || dfs(line[v], t)) {
            line[v] = u;
            return true;
        }
    }
    return false;
}

int solve(int n) {
    for(int i = 1; i <= n; i++) if(!dfs(i, i)) return i-1;
    return n;
}

int main() {
    memset(head, -1, sizeof(head));
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d%d", &x, &y);
        add_edge(x, i);
        add_edge(y, i);
    }
    printf("%d\n", solve(n));
    return 0;
}

你可能感兴趣的:(作业,大视野,二分图匹配,匈牙利算法)