Cod sursa(job #2381478)

Utilizator greelioGreenio Greely greelio Data 16 martie 2019 20:40:48
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include<bits/stdc++.h>
#define N 10010

using namespace std;

const int inf=1e9;
int a[N][N], viz[N];
vector<int>V[2*N];
int s[2*N],n,m,k,rs;
queue<int>Q;


bool BFS(int x) {
    while (Q.size()) Q.pop();
    Q.push(x); viz[1]=-2;
    for (int i=1; i<=n+m+1; ++i) viz[i]=-1;

    while (Q.size()) {
        x=Q.front(); Q.pop();
        for (auto it:V[x]) {
            if (viz[it]==-1 && a[x][it]>0) {
                viz[it]=x;
                if (it==n+m+1) return 1;
                Q.push(it);
            }
        }
    } return 0;
}

int main() {
    ifstream cin("cuplaj.in");
    ofstream cout("cuplaj.out");
    cin>>n>>m>>k;
    for (int i=1; i<=n; ++i) V[0].push_back(i), a[0][i]=1;
    for (int i=n+1; i<=n+m; ++i) V[i].push_back(n+m+1), a[i][n+m+1]=1;
    for (int i=1; i<=k; ++i) {
        int x,y; cin>>x>>y; y+=n;
        V[x].push_back(y);
        V[y].push_back(x);
        a[x][y]=1;
    }
    while (BFS(0)) {
        int flow=inf;
        for (int i=n+m+1; i!=0; i=viz[i]) {
            flow=min(flow,a[viz[i]][i]);
        }
        rs+=flow;
        for (int i=n+m+1; i!=0; i=viz[i]) {
            a[viz[i]][i]-=flow;
            a[i][viz[i]]+=flow;
            s[i]=viz[i];
            s[viz[i]]=0;
        }
    } cout<<rs<<'\n';
    for (int i=n+1; i<=n+m; ++i) {
        if (s[i]) cout<<s[i]<<" "<<i-n<<'\n';
    }
    return 0;
}