Loading

洛谷-P2756 飞行员配对方案问题

飞行员配对方案问题

之前做的,没想到忘了发

二分图匹配最大流问题

模板

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
const int maxn = 110;
int n, m, s, t, tp = 1;
int nex[maxn * maxn], head[maxn], val[maxn * maxn], to[maxn * maxn];
int dep[maxn], cur[maxn];

void add(int u, int v, int w)
{
    tp++;
    nex[tp] = head[u];
    head[u] = tp;
    val[tp] = w;
    to[tp] = v;
}

int bfs()
{
    queue<int>q;
    q.push(s);
    for(int i=0; i<=n; i++) dep[i] = 0;
    for(int i=0; i<=n; i++) cur[i] = head[i];
    dep[s] = 1;
    while(q.size())
    {
        int now = q.front();
        q.pop();
        for(int i=head[now]; i; i=nex[i])
        {
            int u = to[i];
            if(val[i] > 0 && dep[u] == 0)
            {
                dep[u] = dep[now] + 1;
                q.push(u);
            }
        }
    }
    return dep[t];
}

int dfs(int now, int flow)
{
    if(now == t) return flow;
    int ans = 0;
    for(int i=cur[now]; i && ans < flow; i=nex[i])
    {
        int u = to[i];
        cur[now] = i;
        if(val[i] <= 0 || dep[u] != dep[now] + 1) continue;
        int x = dfs(u, min(val[i], flow - ans));
        ans += x;
        val[i] -= x;
        val[i ^ 1] += x;
    }
    return ans;
}

int dinic()
{
    int ans = 0;
    while(bfs())
        ans += dfs(s, n);
    return ans;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> m >> n;
    s = n + 1, t = n + 2;
    int x, y;
    while(cin >> x >> y)
    {
        if(x == -1) break;
        add(x, y, 1);
        add(y, x, 0);
    }
    for(int i=1; i<=m; i++)
    {
        add(s, i, 1);
        add(i, s, 0);
    }
    for(int i=m+1; i<=n; i++)
    {
        add(i, t, 1);
        add(t, i, 0);
    }
    n += 2;
    cout << dinic() << endl;

    for(int i=1; i<=m; i++)
    {
        for(int j=head[i]; j; j=nex[j])
        {
            if(to[j] == s || to[j] == t || val[j]) continue;
            cout << i << " " << to[j] << endl;
        }
    }
    return 0;
}
posted @ 2022-06-21 16:08  dgsvygd  阅读(25)  评论(0编辑  收藏  举报