Cod sursa(job #2188211)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 26 martie 2018 23:56:59
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>

using namespace std;

const string fisier = "cuplaj";
const int nmax = 10005, inf = 2000000000;
int n, m, e, pairu[nmax], pairv[nmax], dist[nmax];
vector<int> v[nmax];

bool bfs()
{
    queue<int> q;
    for (int i = 1; i <= n; ++i)
        if(pairu[i] == 0){
            q.push(i);
            dist[i] = 0;
        }else dist[i] = inf;
    dist[0] = inf;
    while(!q.empty()){
        int k = q.front();
        q.pop();
        if(dist[k] < dist[0])
            for (vector<int>::iterator it = v[k].begin(); it != v[k].end(); ++it)
                if(dist[pairv[*it]] == inf){
                    dist[pairv[*it]] = dist[k]+1;
                    q.push(pairv[*it]);
                }
    }
    return dist[0] != inf;
}

bool dfs(int x)
{
    if(x != 0){
        for (vector<int>::iterator it = v[x].begin(); it != v[x].end(); ++it)
            if(dist[pairv[*it]] == dist[x]+1 && dfs(pairv[*it])){
                pairu[x] = *it;
                pairv[*it] = x;
                return true;
            }
        return false;
    }
    return true;
}

int main()
{
    ifstream fin (fisier+".in");
    ofstream fout (fisier+".out");
    fin >> n >> m >> e;
    for (int i = 1; i <= e; ++i){
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
    }
    int matches = 0;
    while(bfs())
        for (int i = 1; i <= n; ++i)
            if(pairu[i] == 0 && dfs(i))
                ++matches;
    fout << matches << "\n";
    for (int i = 1; i <= n; ++i)
        if(pairu[i] != 0)
            fout << i << " " << pairu[i] << "\n";
    return 0;
}