Cod sursa(job #2618674)

Utilizator nicolaefilatNicolae Filat nicolaefilat Data 25 mai 2020 18:29:52
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <assert.h>

const int MAXN = 10001;

using namespace std;

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

vector<int>graf[MAXN];
int n,m,boss_left[MAXN],boss_right[MAXN];
bool viz[MAXN];

void afis(){

    cout<<"cuplajul este : \n";
    for(int i = 1; i <= n; i++){
        if(boss_right[i])
            cout<<i<<" "<<boss_right[i]<<endl;
    }
    cout<<"======="<<endl;
}

bool cuplaj(int nod){
    if(viz[nod])
        return false;
    viz[nod] = true;
    for(auto vecin : graf[nod]){
        if(boss_left[vecin] == 0){
            boss_left[vecin] = nod;
            boss_right[nod] = vecin;
            return true;
        }
    }
    for(auto vecin : graf[nod]){
        if(cuplaj(boss_left[vecin])){
            boss_left[vecin] = nod;
            boss_right[nod] = vecin;
            return true;
        }
    }

    return false;
}

int main()
{
    int muchii;
    in>>n>>m>>muchii;

    for(int i = 1; i <= muchii; i++){
        int x,y;
        in>>x>>y;
        graf[x].push_back(y);
    }
    int cnt = 0;
    while(true){
        cnt = 0;
        int copie = cnt;
        for(int i = 1; i <= n; i++)
            if(boss_right[i] == 0)
                cnt += cuplaj(i);
        for(int i = 1; i <= n; i++)
            viz[i] = false;
        if(cnt == 0)
            break;
    }
    for(int i = 1; i <= n; i++)
        if(boss_right[i] != 0)
            cnt++;
    out<<cnt<<"\n";
    for(int i = 1; i <= n; i++)
        if(boss_right[i])
            out<<i<<" "<<boss_right[i]<<"\n";
    return 0;
}