Cod sursa(job #3198086)

Utilizator FredyLup Lucia Fredy Data 28 ianuarie 2024 12:47:43
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
/******************************************************************************

                            Online C Compiler.
                Code, Compile, Run and Debug C program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <stdio.h>
#include <fstream>
#include <vector>

using namespace std;

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

#define limn 10010
int N, M, E, A[limn], B[limn];
vector <int> G[limn];
bool viz[limn];

bool pairUp(int node) {
    if(viz[node])   
        return false;
    viz[node] = true;
    
    for(auto it:G[node]) // node face parte din A
        if(!B[it]) { // combinam node cu it 
            B[it] = node;
            A[node] = it;
            return true;
        }
    
    for(auto it:G[node])
        if(pairUp(B[it])) { // putem 'strica' perechea de la B[it], asa ca combinam node cu it
            B[it] = node;
            A[node] = it;
            return true;
        }
        
    return false;
}

int main()
{
    int x, y;
    fin>>N>>M>>E;
    for(int i = 1; i <= E; i++) {
        fin>>x>>y;
        G[x].push_back(y);
    }
    
    bool pathFound = true; // gasim un lant augumentat
    while(pathFound) {
        pathFound = false;
        for(int i = 1; i <= N; i++) // initializare viz
            viz[i] = 0;
        
        for(int i = 1; i <= N; i++)
            if(!A[i])
               pathFound |= pairUp(i);
    }
    
    int nrMatches = 0;
    for(int i = 1; i <= N; i++)
        if(A[i])
            nrMatches++;
    fout<<nrMatches<<'\n';
    for(int i = 1; i <= N; i++)
        if(A[i])
            fout<<i<<' '<<A[i]<<'\n';
    
    return 0;
}