Cod sursa(job #1596746)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 11 februarie 2016 12:52:25
Problema Cuplaj maxim in graf bipartit Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
 
static bool try_to_repair(const int x, const vector<vector<int>>& graf, vector<int>& right, vector<int>& left, vector<bool>& used){
    if(used[x]){
        return false; }
    used[x] = true;
    for(const auto y : graf[x]){
        if(left[y] == -1){
            right[x] = y;
            left[y] = x;
            return true; } }
    for(const auto y : graf[x]){
        if(try_to_repair(left[y], graf, right, left, used)){
            right[x] = y;
            left[y] = x;
            return true; } }
    return false; }
 
int main(){
    ifstream f("cuplaj.in");
    ofstream g("cuplaj.out");
    int n, m, e;
 
    f >> n >> m >> e;
 
    static vector<vector<int>> graf(n);
    for(int i = 0, a, b; i < e; ++i){
        f >> a >> b;
        graf[a-1].push_back(b-1); }
 
    static vector<int> right(n, -1), left(m, -1);
    static vector<bool> used(n, false);
 
    for(bool changed = true; changed; ){
        changed = false;
        fill(begin(used), end(used), false);
        for(int i = 0; i < n; ++i){
            if(right[i] == -1){
                changed = (try_to_repair(i, graf, right, left, used) || changed); } } }
 
    const int sz_cuplaj = count_if(begin(right), end(right), [](const int x){ return x != -1; });
    g << sz_cuplaj << endl;
    for(int i = 0; i < n; ++i){
        if(right[i] != -1){
            g << i+1 << ' ' << right[i]+1 << endl; } }
 
    return 0; }