Cod sursa(job #2694863)

Utilizator nicolaefilatNicolae Filat nicolaefilat Data 10 ianuarie 2021 22:50:40
Problema Cuplaj maxim in graf bipartit Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 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

vector<int>path;
int n,m,muchii;
bool stiva[MAXN];

void debug(){
    cout<<"Augmented path\n";
    for(int i = 0; i < path.size(); i += 2)
        cout<<"("<<path[i]<<" "<<path[i + 1]<<") ";
    cout<<"\n";
}
void print_path(){
    cout<<"Current path\n";
    for(int i = 0; i < path.size(); i++){
        if(i + 1 >= path.size())
            cout<<path[i]<<" ";
        else
            cout<<"("<<path[i]<<" "<<path[i + 1]<<") ";
    }
    cout<<"\n";
}

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

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

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++)
//            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;
}