POJ1422 Air Raid

PS: 1. 有向图 2.不存在环 即DAG。网上有对图进行拆点然后求解最大匹配,有的直接对原图求最大匹配。

如果对图进行拆点,重构新图:

首先建图:先拆点,将每个点分为两个点,左边是1到n个点,右边是1-n个点
然后每一条有向边对应左边的点指向右边的点
这样建好图之后求最大匹配数
因为最小路径覆盖=点数-最大匹配数

两份代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX = 130;
vector<int> G[MAX];
int n, m;
int from[MAX], tot;
bool use[MAX];

bool match(int x) {
    for(int i = 0; i < (int)G[x].size(); i++) {
        int &u = G[x][i];
        if(!use[u]) {
            use[u] = true;
            if(from[u]==-1 || match(from[u])) {
                from[u] = x;
                return true;
            }
        }
    }
    return false;
}

int hungary() {
    tot = 0;
    memset(from, 255, sizeof(from));
    for(int i = 1; i <= n; i++) {
        memset(use, 0, sizeof(use));
        if(match(i)) {
            tot++;
        }
    }
    return tot;
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--) {
        int x, y;
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++) G[i].clear();
        for(int i = 0; i < m; i++) {
            scanf("%d%d", &x, &y);
            G[x].push_back(y);
        }
        int res = hungary();
        printf("%d\n", n-res);
    }
    return 0;
}


#include<iostream>
#include<vector>
#include <cstring>
#include <cstdio>
#define N 205
using namespace std;
vector<int> G[N];
int vis[N];
int match[N];
int n;
int dfs(int u)
{
    for(int i = 0; i<(int)G[u].size(); i++){
        int v = G[u][i];
        if(!vis[v]) {
            vis[v] = 1;
            if(match[v]==-1 || dfs(match[v])){
                match[v] = u;
                return 1;
            }
        }
    }
    return 0;
}
int hungary()
{
    memset(match, -1, sizeof(match));
    int ret = 0;
    for(int i=1; i<=n; i++) {
        memset(vis, 0, sizeof(vis));
        ret += dfs(i);
    }
    return ret;
}

int main(void)
{
    int t, m, a, b;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        for(int i=0; i<=n; i++) G[i].clear();
        scanf("%d", &m);
        while(m--) {
            scanf("%d%d", &a, &b);
            G[a].push_back(b);
        }
        printf("%d\n", n-hungary());
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值