Cod sursa(job #2694025)

Utilizator buhaidarius@gmail.comBuhai Darius [email protected] Data 7 ianuarie 2021 20:49:21
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int n, m ,k;
vector<vector<int>> graph;
vector<int> l_pair_up, r_pair_up;
vector<bool> visited;

bool pair_up(int i){
    if(visited[i]) return false;
    visited[i] = true;
    for(auto &pair: graph[i])
        if(!r_pair_up[pair]){
            l_pair_up[i] = pair;
            r_pair_up[pair] = i;
            return true;
        }
    for(auto& pair: graph[i])
        if(pair_up(r_pair_up[pair])){
            l_pair_up[i] = pair;
            r_pair_up[pair] = i;
            return true;
        }
    return false;
}

int main() {
    ifstream fin("cuplaj.in");
    ofstream fout("cuplaj.out");
    fin>>n>>m>>k;
    l_pair_up.resize(n+1, 0);
    r_pair_up.resize(m+1, 0);
    graph.resize(n+1);
    while(k--){
        int x, y;
        fin>>x>>y;
        graph[x].emplace_back(y);
    }
    bool change = true;
    while(change){
        change = false;
        visited.clear();
        visited.resize(n+1, false);
        for(int i=1;i<=n;++i)
            if(!l_pair_up[i])
                change |= pair_up(i);
    }
    int total = 0;
    for(auto &pair: l_pair_up)
        if(pair)
            total++;
    fout<<total<<'\n';
    for(int i=1;i<=n;++i)
        if(l_pair_up[i]>0)
            fout<<i<<' '<<l_pair_up[i]<<'\n';
    return 0;
}