Cod sursa(job #2184437)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 24 martie 2018 01:52:55
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 int nmax = 10005, inf = 2000000000;
int n, m, e, pairu[nmax], pairv[nmax], dist[nmax];
vector<int> v[10005];

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

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

int main()
{
    ifstream fin ("cuplaj.in");
    ofstream fout ("cuplaj.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;
}