Cod sursa(job #2887049)

Utilizator DordeDorde Matei Dorde Data 8 aprilie 2022 18:58:32
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include<bits/stdc++.h>
#define inf (1<<30)
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
int const N = 10001;
int n , m , e;
int st[N] , dr[N] , lv[N];///st[i] -> cuplajul din L al lui i
///L R
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;///nod cuplat [i dr[y]]
    lv[0] = inf;///nodurile necuplate sunt cuplate cu 0
    while(!q.empty()){
        auto x = q.front();
        q.pop();
        if(lv[x] < lv[0]){///daca il cuplez pe 0 cu cineva inseamna ca am gasit cuplaj din lant de lungime minimia, nu are rost sa caut mai adanc
            for(auto y : v[x]){
                ///ma duc pe muchia [x , y] NECUPLATA
                ///verific daca y e cuplat
                if(lv[st[y]] == inf){///y e cuplat cu st[y]
                    lv[st[y]] = 1 + lv[x];///[x , y] , [y , st[y]] , ...
                    q.push(st[y]);
                }
            }
        }
    }
    return lv[0] != inf;///am gasit minim un lant alternant
}
bool dfs(int x){
    if(x != 0){
        for(auto 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;

    }
    return true;
}
int maxmatch(){
    int r = 0;
    fill(st , st + n + 1 , 0);
    fill(dr , dr + m + 1 , 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);///L->R
    }
    fout << maxmatch() << '\n';
    for(int i = 1 ; i <= n ; ++ i)
        if(dr[i]) fout << i << ' ' << dr[i] << '\n';
    return 0;
}