Cod sursa(job #2976698)

Utilizator DordeDorde Matei Dorde Data 9 februarie 2023 21:01:35
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
int const N = 1e4 + 3 , inf = (1 << 30);
int n , m , e;
int st[N] , dr[N] , lv[N];
vector<int> v[N];
bool bfs(){
    queue<int> q;
    for(int i = 1 ; i <= n ; ++ i)
        if(!dr[i])
            q.push(i) , lv[i] = 0;
        else
            lv[i] = inf;
    lv[0] = inf;
    while(!q.empty()){
        int x = q.front();
        q.pop();
        if(lv[x] >= lv[0])
            continue;
        for(int y : v[x]){
            if(lv[st[y]] == inf){
                lv[st[y]] = 1 + lv[x];
                q.push(st[y]);
            }
        }
    }
    return lv[0] != inf;
}
bool dfs(int x){
    if(x == 0)
        return false;
    for(int y : v[x]){
        if(lv[st[y]] == 1 + lv[x] && dfs(st[y])){
            st[y] = x;
            dr[x] = y;
            return true;
        }
    }
    lv[x] = inf;
    return false;
}
int maxmatch(){
    int r = 0;
    while(bfs()){
        for(int i = 1 ; i <= n ; ++ i)
            if(!dr[i] && dfs(i))
                ++ r;
    }
    return r;
}
int main()
{
    fin >> n >> m >> e;
    for(int i = 1 ; i <= e ; ++ i){
        int x , y;
        fin >> x >> y;
        v[x].push_back(y);
    }
    fout << maxmatch() << '\n';
    for(int i = 1 ; i <= n ; ++ i)
        if(dr[i])
            fout << i << ' ' << dr[i] << '\n';
    return 0;
}