Cod sursa(job #2233554)

Utilizator alextodoranTodoran Alexandru Raul alextodoran Data 23 august 2018 16:47:48
Problema Cuplaj maxim in graf bipartit Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <bits/stdc++.h>

#define NM 20005

using namespace std;

vector <int> G[NM];

int C[NM][NM], F[NM][NM];
int T[NM];
int nr;

int n, m, L, e;

queue <int> q;

bool BFS()
{
    for(int i = 0; i <= L + 1; i++)
        T[i] = -1;
    q.push(0);
    while(!q.empty())
    {
        int f = q.front();
        q.pop();
        for(auto i : G[f])
            if(T[i] == -1 && F[f][i] < C[f][i])
            {
                T[i] = f;
                q.push(i);
            }
    }
    return (T[L + 1] > 0);
}

int main()
{
    ifstream fin ("cuplaj.in");
    ofstream fout ("cuplaj.out");
    fin >> n >> m >> e;
    L = n + m;
    for(int i = 1; i <= e; i++)
    {
        int a, b;
        fin >> a >> b;
        b += n;
        G[a].push_back(b);
        G[b].push_back(a);
        C[a][b] = 1;
    }
    for(int i = 1; i <= n; i++)
    {
        G[0].push_back(i);
        G[i].push_back(0);
        C[0][i] = 1;
    }
    for(int i = n + 1; i <= L; i++)
    {
        G[i].push_back(L + 1);
        G[L + 1].push_back(i);
        C[i][L + 1] = 1;
    }
    while(BFS())
    {
        int mi = -1;
        for(int i = L + 1; i > 0; i = T[i])
            if(C[T[i]][i] - F[T[i]][i] < mi || mi == -1)
                mi = C[T[i]][i] - F[T[i]][i];
        for(int i = L + 1; i > 0; i = T[i])
        {
            F[T[i]][i] += mi;
            F[i][T[i]] -= mi;
        }
        nr += mi;
    }
    fout << nr << "\n";
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            if(F[i][j + n] > 0)
                fout << i << " " << j << "\n";
    return 0;
}