Cod sursa(job #2694865)

Utilizator nicolaefilatNicolae Filat nicolaefilat Data 10 ianuarie 2021 22:54:30
Problema Cuplaj maxim in graf bipartit Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <iostream>
#include <vector>
#include <fstream>

const int MAXN = 1e5 + 1;

using namespace std;

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

vector<int>graf[MAXN];
bool viz[MAXN];
int boss_dr[MAXN],boss_st[MAXN];/// boss_dr[l] = r, cuplez stanga cu dreapta
int n,m,muchii;

bool has_augmented_path(int nod_st){
    viz[nod_st] = true;

    for(int nod_dr : graf[nod_st]){
        if(boss_st[nod_dr] == 0){
            /// am un augmented path de lungime 2
            boss_st[nod_dr] = nod_st;
            boss_dr[nod_st] = nod_dr;
//            viz[nod_st] = false;
            return true;
        }
    }
    for(int nod_dr : graf[nod_st]){
        /// acum nod_dr e cuplaj cu cineva
        int cuplat = boss_st[nod_dr];
        if(!viz[cuplat] && has_augmented_path(cuplat)){
            boss_st[nod_dr] = nod_st;
            boss_dr[nod_st] = nod_dr;
//            viz[nod_st] = false;
            return true;
        }
    }
//    viz[nod_st] = false;
    return false;
}

int main()
{
    in>>n>>m>>muchii;
    for(int i = 1; i <= muchii; i++){
        int x,y;
        in>>x>>y;
        graf[x].push_back(y);
    }
    bool augmented_path = true;
    while(augmented_path){
        augmented_path = false;
        for(int i = 1; i <= n; i++){
            if(!viz[i]){
                augmented_path |= has_augmented_path(i);
//                viz[i] = false;
            }
        }
        for(int i = 1; i <= n; i++){
            viz[i] = false;
        }
//        for(int i = 1; i <= n; i++)
//            cout<<viz[i]<<" ";
//        cout<<endl;
    }
    int card = 0;
    for(int i = 1; i <= n; i++)
        if(boss_dr[i])
            card++;
    out<<card<<"\n";
    for(int i = 1; i <= n; i++)
        if(boss_dr[i])
            out<<i<<" "<<boss_dr[i]<<"\n";

    return 0;
}