大视野 1854 游戏 匈牙利算法

来源:互联网 发布:局域网内文件传输软件 编辑:程序博客网 时间:2024/05/18 02:39

题目: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<cstdio>#include<cstring>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;}
0 0
原创粉丝点击