大视野 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<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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值