Cod sursa(job #2004434)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 25 iulie 2017 22:06:29
Problema Cuplaj maxim in graf bipartit Scor 24
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <queue>

using namespace std;

const int inf = 2000000000;

vector<int> adj[10005];
int n, m, e, pairu[10005], pairv[10005], dist[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 = adj[u].begin(); it != adj[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 x)
{
    if(x != 0){
        for (vector<int>::iterator it = adj[x].begin(); it != adj[x].end(); ++it)
            if(dist[pairv[*it]] == dist[x] + 1){
                pairv[*it] = x;
                pairu[x] = *it;
                return true;
            }
        dist[x] = inf;
        return false;
    }
    return true;
}

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