【网络流24题】搭配飞行员(二分图最大匹配)

题意

飞行大队有若干个来自各地的驾驶员,专门驾驶一种型号的飞机,这种飞机每架有两个驾驶员,需一个正驾驶员和一个副驾驶员。由于种种原因,例如相互配合的问题,有些驾驶员不能在同一架飞机上飞行,问如何搭配驾驶员才能使出航的飞机最多。

因为驾驶工作分工严格,两个正驾驶员或两个副驾驶员都不能同机飞行。

题解

二分图最大匹配。
建立源点和汇点,源点连左边点集,容量为1;右边点集连汇点,容量为1.
中间的点,左边点集中的点向右边点集的点连边,容量为1。
跑最大流即可。

代码


#include
using namespace std;
typedef double db;
typedef long long ll;
typedef unsigned long long ull;
const int nmax = 205;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const ull p = 67;
const ull MOD = 1610612741;
struct Dinic {
    int head[nmax], cur[nmax], d[nmax];
    bool vis[nmax];
    int tot, n, m, s, t, front, tail;
    int qqq[nmax];
    struct edge {
        int nxt, to, w, cap, flow;
    } e[nmax<<1];
    void init(int n) {
        this->n = n;
        memset(head, -1, sizeof head);
        memset(e,0,sizeof e);
        this->tot = 0;
    }
    int add_edge(int u, int v, int c) {
        int temp = tot;
        e[tot].to = v, e[tot].cap = c, e[tot].flow = 0;
        e[tot].nxt = head[u];
        head[u] = tot++;
        e[tot].to = u, e[tot].cap = c, e[tot].flow = c;
        e[tot].nxt = head[v];
        head[v] = tot++;
        return temp;
    }
    bool BFS() {
//        memset(vis, 0, sizeof(vis));
//        queueQ;
        for(int i = 0; i <= n; ++i) vis[i] = false;
        front = tail = 0;
        vis[s] = 1; d[s] = 0;
//        Q.push(s);
        qqq[tail++] = s;
        while (front < tail) {
//            int u = Q.front(); Q.pop();
            int u = qqq[front++];
            for (int i = head[u]; i != -1; i = e[i].nxt) {
                int v = e[i].to;
                if (!vis[v] && e[i].cap > e[i].flow) {
                    vis[v] = 1;
                    d[v] = d[u] + 1;
//                    Q.push(v);
                    qqq[tail++] = v;
                }
            }
        }
        return vis[t];
    }
    int DFS(int x, int a) {
        if (x == t || a == 0) return a;
        int Flow = 0, f;
        for (int& i = cur[x]; i != -1; i = e[i].nxt) {
            int v = e[i].to;
            if (d[v] == d[x] + 1 && (f = DFS(v, min(a, e[i].cap - e[i].flow))) > 0) {
                Flow += f;
                e[i].flow += f;
                e[i ^ 1].flow -= f;
                a -= f;
                if (a == 0) break;
            }
        }
        return Flow;
    }
    int Maxflow(int s, int t) {
        this->s = s, this->t = t;
        int Flow = 0;
        while (BFS()) {
            for (int i = 0; i <= n; i++) cur[i] = head[i];
            Flow += DFS(s,INF);
        }
        return Flow;
    }
} dinic;
int n, m;
int main(){
    scanf("%d %d", &n, &m);
    int s = 0, t = n + 1;
    int u, v;
    dinic.init(n + 1);
    while(scanf("%d %d", &u, &v) != EOF) {
        dinic.add_edge(u, v, 1);
    }
    for(int i = 1; i <= m; ++i) {
        dinic.add_edge(s, i, 1);
    }
    for(int i = m + 1; i <= n; ++i) {
        dinic.add_edge(i, t, 1);
    }
    printf("%d\n", dinic.Maxflow(s, t));
    return 0;
}

你可能感兴趣的:(图论---网络流)