Cod sursa(job #2372504)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 7 martie 2019 09:35:11
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
#define ff first
#define ss second

using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;

const string file = "cuplaj";
const ll INF = 9223372036854775807ll;
const int inf = 2147483647, nmax = 10005;

int n1, n2, m, pairu[nmax], pairv[nmax], dist[nmax];
vector<int> v[nmax];

bool bfs()
{
    for (int i = 0; i <= n1; ++i)
        dist[i] = inf;
    queue<int> q;
    for (int i = 1; i <= n1; ++i)
        if(!pairu[i]){
            q.push(i);
            dist[i] = 0;
        }
    while(!q.empty()){
        int k = q.front();
        q.pop();
        if(dist[k] >= dist[0])
            continue;
        for (auto x : v[k])
            if(dist[pairv[x]] == inf){
                dist[pairv[x]] = dist[k]+1;
                q.push(pairv[x]);
            }
    }
    return dist[0] != inf;
}

int dfs(int x)
{
    if(!x)
        return true;
    for (auto y : v[x])
        if(dist[pairv[y]] == dist[x]+1)
            if(dfs(pairv[y])){
                pairu[x] = y;
                pairv[y] = x;
                return true;
            }
    //dist[x] = inf; //why
    return false;
}

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