Cod sursa(job #1161857)

Utilizator muresan_bogdanMuresan Bogdan muresan_bogdan Data 31 martie 2014 15:05:55
Problema Cuplaj maxim in graf bipartit Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb
#include<iostream>
#include<fstream>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int MAXN = 20005;
const int INF = 1000000000;

int n, m, k, i, flow, fmax, dest, tata[MAXN], x, y;
short c[MAXN][MAXN], f[MAXN][MAXN];
bool viz[MAXN];
vector<int> g[MAXN];
queue<int> coada;

bool BFS() {
    memset(viz, 0, sizeof(viz));
    coada.push(0);
    viz[0] = 1;
    while(!coada.empty()) {
        int nod = coada.front();
        coada.pop();
        if(nod != dest) {
            for(int j = 0; j < g[nod].size(); j++) {
                int v = g[nod][j];
                if(f[nod][v] != c[nod][v] && !viz[v]) {
                    viz[v] = 1;
                    tata[v] = nod;
                    coada.push(v);
                }
            }
        }
    }
    return viz[dest];
}

int main() {
    fin >> n >> m >> k;
    dest = n + m + 1;
    for(i = 0; i < k; i++) {
        fin >> x >> y;
        c[x][y+n] = 1;
        g[x].push_back(y+n);
        g[y+n].push_back(x);
    }
    for(i = 1; i <= n; i++) {
        c[0][i] = 1;
        g[0].push_back(i);
        g[i].push_back(0);
    }
    for(i = 1; i <= m; i++) {
        c[n+i][dest] = 1;
        g[n+i].push_back(dest);
        g[dest].push_back(n+i);
    }
    flow = 0;
    while(BFS()) {
        for(int j = 0; j < g[dest].size(); j++) {
            int v = g[dest][j];
            if(c[v][dest] != f[v][dest] && viz[v]) {
                tata[dest] = v;
                fmax = INF;
                v = dest;
                while(v != 0) {
                    fmax = min(fmax, c[tata[v]][v] - f[tata[v]][v]);
                    v = tata[v];
                }
                if(fmax != 0) {
                    v = dest;
                    while(v != 0) {
                        f[tata[v]][v] += fmax;
                        f[v][tata[v]] -= fmax;
                        v = tata[v];
                    }
                }
                flow += fmax;
            }
        }
    }
    fout << flow << '\n';
    for(int j = 0; j < g[dest].size(); j++) {
        int v = g[dest][j];
        if(tata[v]) {
            fout << tata[v] << ' ' << v - n << '\n';
        }
    }
    fin.close();
    fout.close();
    return 0;
}