Cod sursa(job #1957598)

Utilizator razvandRazvan Dumitru razvand Data 7 aprilie 2017 17:28:35
Problema Cuplaj maxim in graf bipartit Scor 8
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <climits>

using namespace std;

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

int n,m,e;
int N;
int bef[2*10003];
bool viz[2*10003];
unordered_map<int, int> v[2*10003];
vector<int> E[2*10003];

bool bfs() {

    for(int i = 0; i <= N; i++)
        viz[i] = false;

    queue<int> Q;
    Q.push(0);
    viz[0] = true;
    int nod;
    int nx;

    while(!Q.empty()) {

        nod = Q.front();
        Q.pop();

        for(int i = 0; i < E[nod].size(); i++) {

            nx = E[nod][i];

            if(viz[nx])
                continue;
            if(v[nod][nx] == 0)
                continue;

            bef[nx] = nod;
            viz[nx] = true;
            Q.push(nx);

        }

    }

    if(viz[N])
        return true;
    return false;

}

int main() {

    in >> n >> m >> e;
    int x,y;

    for(int i = 1; i <= e; i++) {
        in >> x >> y;
        v[x][n+y] = INT_MAX/2;
        E[x].push_back(n+y);
        E[n+y].push_back(x);
    }

    N = n+m+1;

    for(int i = 1; i <= n; i++) {
        v[0][i] = 1;
        E[0].push_back(i);
        E[i].push_back(0);
    }

    for(int i = 1; i <= m; i++) {
        v[n+i][N] = 1;
        E[n+i].push_back(N);
        E[N].push_back(n+i);
    }

    int ans = 0;

    while(bfs()) {

        for(int i = n+1; i <= n+m; i++) {

            if(!viz[i])
                continue;

            bef[N] = i;
            int crr = N;

            while(crr != 0) {
                //cout << crr << " ";
                v[bef[crr]][crr]--;
                v[crr][bef[crr]]++;
                crr = bef[crr];
            }

            //cout << '\n';

            ans++;

        }

    }

    int nx = 0;
    out << ans << '\n';

    for(int i = 1; i <= n; i++) {

        for(int j = 0; j < E[i].size(); j++) {

            nx = E[i][j];

            if(nx == 0)
                continue;

            if(v[i][nx] != INT_MAX/2) {
                out << i << " " << nx-n << '\n';
                break;
            }

        }

    }

    return 0;
}