Cod sursa(job #2204970)

Utilizator gabib97Gabriel Boroghina gabib97 Data 17 mai 2018 13:35:50
Problema Taramul Nicaieri Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.78 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
#include <climits>

#define N 205
using namespace std;

int n, t[N], C[N][N], in[N], out[N], drain;
vector<int> G[N];
vector<pair<int, int>> edges;

int bfs() {
    int s;
    queue<int> Q;
    Q.push(0);
    for (int i = 0; i <= drain; i++)
        t[i] = -1;

    while (!Q.empty()) {
        s = Q.front();
        Q.pop();

        for (int &x : G[s])
            if (C[s][x] > 0 && t[x] == -1) {
                t[x] = s;
                Q.push(x);
            }
    }

    return t[drain] > -1;
}

int max_flow() {
    int flow = 0, w;

    while (bfs()) {
        w = INT_MAX;

        for (int x = drain; x != 0; x = t[x])
            w = min(w, C[t[x]][x]);

        flow += w;
        for (int x = drain; x != 0; x = t[x]) {
            C[t[x]][x] -= w;
            C[x][t[x]] += w;
        }
    }

    return flow;
}

int main() {
    ifstream cin("harta.in");
    ofstream cout("harta.out");

    int i, j;
    cin >> n;
    drain = 2 * n + 1;
    for (i = 1; i <= n; i++) {
        cin >> out[i] >> in[i];
        C[0][i] = in[i];
        C[n + i][drain] = out[i];

        G[0].push_back(i);
        G[i].push_back(0);

        G[n + i].push_back(drain);
        G[drain].push_back(n + i);
    }

    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++)
            if (i != j) {
                G[i].push_back(n + j);
                G[n + j].push_back(i);
                C[i][n + j] = 1;
            }

    max_flow();
    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++)
            if (i != j && C[i][n + j] == 0)
                edges.push_back(make_pair(i, j));

    cout << edges.size() << '\n';
    for (auto &p : edges)
        cout << p.first << ' ' << p.second << '\n';
    return 0;
}