Cod sursa(job #2209906)

Utilizator GeorgianBaditaBadita Marin-Georgian GeorgianBadita Data 4 iunie 2018 23:54:03
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>
#include <cstring>
#define NMAX 10005
using namespace std;

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");

vector<int> G[NMAX];
int left_m[NMAX], right_m[NMAX];
bool viz[NMAX];
int n, m, edg;

void read_data(){
    f >> n >> m >> edg;
    for(int i = 1; i<=edg; i++){
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
    }
}

bool find_match(int node){
    if(viz[node]){
        return false;
    }
    viz[node] = true;
    for(const auto& adj:G[node]){
        if(!right_m[adj]){
            left_m[node] = adj;
            right_m[adj] = node;
            return true;
        }
    }
    for(const auto& adj : G[node]){
        if(find_match(right_m[adj])){
            left_m[node] = adj;
            right_m[adj] = node;
            return true;
        }
    }
    return false;
}

void solve(){
    int changed = 1;
    while(changed){
        changed = 0;
        memset(viz, false, sizeof(viz));
        for(int i = 1; i<=n; i++){
            if(!left_m[i]){
                changed |= find_match(i);
            }
        }

    }

    int nr_c = 0;
    for(int i = 1; i<=n; i++){
        if(left_m[i] > 0){
            nr_c ++;
        }
    }
    g << nr_c << '\n';
    for(int i = 1; i<=n; i++){
        if(left_m[i] > 0){
            g << i << ' ' << left_m[i] << '\n';
        }
    }
}

int main(){
    read_data();
    solve();
    return 0;
}