P2756 飞行员配对方案问题 【网络流24题 最大流】

传送门

废话:最大流模板题

思路:二分匹配也可以写,最简单的网络流,只需要增加超级源点和超级汇点即可
超级源点->外籍飞行员 (流上限为1)
外籍飞行员->英国飞行员(流上限为1) 
英国飞行员->超级汇点(流上限为1)
最大流就是最多匹配数,我们可以通过每条边的反向边来判断是否匹配

代码:

///#include
///#include
///#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

#define MT(a, b) memset(a,b,sizeof(a)
#define lowbit(x) (x&(-x))
using namespace std;
typedef long long ll;
const double pai = acos(-1.0);
const double E = 2.718281828459;
const ll mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
const double esp = 1e-6;
const int maxn = 1e5 + 5;

int depth[maxn], Sta, End;
struct node {
    int e, c, p;
} load[maxn * 2];
int head[maxn], sign;

void add_edge(int s, int e, int c) {
    load[++sign] = node{e, c, head[s]};
    head[s] = sign;
}


bool bfs() {
    queue q;
    memset(depth, -1, sizeof(depth));
    depth[Sta] = 1;
    q.push(Sta);
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = head[u], v; ~i; i = load[i].p) {
            v = load[i].e;
            if (load[i].c > 0 && depth[v] == -1) {
                depth[v] = depth[u] + 1;
                q.push(v);
            }
        }
    }
    return depth[End] != -1;
}

int dfs(int s, int cost) {
    if (s == End) return cost;
    for (int i = head[s], e; ~i; i = load[i].p) {
        e = load[i].e;
        if (depth[e] == depth[s] + 1 && load[i].c != 0) {
            int c = dfs(e, min(cost, load[i].c));
            if (c > 0) {
                load[i].c -= c;
                load[i ^ 1].c += c;
                return c;
            }
        }
    }
    return 0;
}

void init() {
    sign = -1;
    memset(head, -1, sizeof(head));
}

int main() {
    init();
    int m, n, s, e;
    scanf("%d %d", &m, &n);
    Sta = 0, End = n + m + 1;
    while (scanf("%d %d", &s, &e) && s + e + 2) {
        e += m;
        add_edge(s, e, 1);
        add_edge(e, s, 0);
    }
    for (int i = 1; i <= m; i++) {
        add_edge(0, i, 1);
        add_edge(i, 0, 0);
    }
    for (int i = 1; i <= n; i++) {
        add_edge(n + i, n + m + 1, 1);
        add_edge(n + m + 1, n + i, 0);
    }
    int ans = 0;
    while (bfs()) ans += dfs(Sta, INF);
    if (ans == 0) {
        printf("No Solution!\n");
        return 0;
    }
    printf("%d\n", ans);
    for (int u = 1; u <= m; u++) {
        for (int i = head[u], v; ~i; i = load[i].p) {
            v = load[i].e;
            if (v && load[i].c == 0) {
                printf("%d %d\n", u, v - m);
            }
        }
    }
    return 0;
}

 

你可能感兴趣的:(网路流24题)