求助..初学网络流ek练手63QAQ
查看原帖
求助..初学网络流ek练手63QAQ
569401
YYY955楼主2022/7/27 18:58
#include <bits/stdc++.h>
using namespace std;
const int N = 1000, M = N * N;
int m, n, s, t, mf;
int tot = 1, h[N], ne[M], to[M], e[M], incf[N], pre[N];
bool v[N];
set<pair<int, int>> path;
void add(int x, int y, int z)
{
    to[++tot] = y, e[tot] = z, ne[tot] = h[x], h[x] = tot;
    to[++tot] = x, e[tot] = 0, ne[tot] = h[y], h[y] = tot;
}

bool bfs()
{
    memset(v, 0, sizeof v);
    queue<int> q;
    q.push(s);
    v[s] = 1;
    incf[s] = 0x3f3f3f;
    while (q.size())
    {
        int x = q.front();
        q.pop();
        for (int i = h[x]; i; i = ne[i])
        {
            if (e[i])
            {
                int y = to[i];
                if (!v[y])
                {
                    incf[y] = min(incf[x], e[i]);
                    pre[y] = i;
                    q.push(y), v[y] = 1;
                    if (y == t)
                        return 1;
                }
            }
        }
    }
    return 0;
}

void update()
{
    int x = t;
    while (x != s)
    {
        int i = pre[x]; //前驱点对应的tot编号
        e[i] -= incf[t];
        e[i ^ 1] += incf[t];
        if (x != t && to[i ^ 1] != s)
        {
            path.insert({to[i ^ 1], x});
        }
        x = to[i ^ 1]; // i对应的起点;
    }
    mf += incf[t];
}

int main()
{
    cin >> m >> n;
    int x, y;
    s = 0, t = n + 1, mf = 0;
    for (int i = 1; i <= n; i++)
    {
        if (i <= m)
            add(s, i, 1);
        else
            add(i, t, 1);
    }
    while (scanf("%d%d", &x, &y))
    {
        if ((x == -1 && y == -1))
            break;
        add(x, y, 1);
    }
    while (bfs())
    {
        // cout << pre[t] << ' ' << (pre[t] ^ 1) << endl;
        update();
    }
    cout << mf;
    for (auto i : path)
    {
        cout << '\n'
             << i.first << " " << i.second;
    }
    system("pause");
    return 0;
}
2022/7/27 18:58
加载中...