Cod sursa(job #2694857)

Utilizator nicolaefilatNicolae Filat nicolaefilat Data 10 ianuarie 2021 22:08:05
Problema Cuplaj maxim in graf bipartit Scor 24
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.6 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[MAXN];/// boss[r] = r este cuplaj cu boss[r] care e in stanga
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,int anterior = -1){
    viz[nod_st] = true;
    path.push_back(nod_st);

//    print_path();

    for(int nod_dr : graf[nod_st]){
        if(!viz[n + nod_dr]){
            /// we have an augmented path
            viz[n + nod_dr] = true;
            path.push_back(nod_dr);
//            debug();
            for(int i = 0; i < path.size(); i += 2){
                boss[path[i]] = path[i + 1];
            }
            return true;
        }else{
            int nod_st_cuplat = boss[nod_dr];
            if(!stiva[nod_st_cuplat]){
                path.push_back(nod_dr);
                stiva[nod_st_cuplat] = true;
                int status = has_augmented_path(nod_st_cuplat,nod_st);
                path.pop_back();
                stiva[nod_st_cuplat] = false;
                if(status)
                    return true;

            }
        }
    }
    path.pop_back();
    stiva[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]){
                path.clear();
//                cout<<"DFS "<<i<<endl;
                stiva[i] = true;
                augmented_path |= has_augmented_path(i);
                stiva[i] = false;
//                for(int i = 1; i <= n; i++)
//                    cout<<stiva[i]<<" ";
//                cout<<endl;
            }
        }
    }
    int card = 0;
    for(int i = 1; i <= n; i++)
        if(boss[i])
            card++;
    out<<card<<"\n";
    for(int i = 1; i <= n; i++)
        if(boss[i])
            out<<i<<" "<<boss[i]<<"\n";

    return 0;
}