Cod sursa(job #2005064)

Utilizator infomaxInfomax infomax Data 26 iulie 2017 14:25:23
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <bits/stdc++.h>

using namespace std;

FILE *F=fopen("cuplaj.in", "r"), *G=fopen("cuplaj.out", "w");

int dist[10002], pairu[10002], pairv[10002], n, m, x, y, e, Match, nr;
vector<int> a[10002];
queue <int> q;
const int inf = 2000000000;

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

int dfs(int nod)
{
    vector<int> :: iterator it;
    if(!nod) return 1;

    for(it = a[nod].begin(); it != a[nod].end(); ++ it)
        if(dist[pairv[*it]] == dist[nod] + 1)
            if(dfs(pairv[*it]))
            {
                pairv[*it] = nod;
                pairu[nod] = *it;
                return 1;
            }
    dist[nod] = inf;
    return 0;
}

int main()
{
    fscanf(F, "%d %d %d ", &n, &m, &e);
    for(int i = 0; i < e; ++ i)
    {
        fscanf(F, "%d %d ", &x, &y);
        a[x].push_back(y);
    }
    while(bfs())
        for(int i = 1; i <= n; ++ i)
            if(!pairu[i] && dfs(i))
                Match ++;
    fprintf(G, "%d\n", Match);
    for(int i = 1; i <= n; ++ i)
        if(pairu[i]) fprintf(G, "%d %d\n", i, pairu[i]);
    return 0;
}