Cod sursa(job #3333294)

Utilizator tudorbeloiuLuka Modric tudorbeloiu Data 12 ianuarie 2026 19:23:33
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;


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

struct Muchie{
    int to;
    int flow;
    int cap;

    Muchie(int _to=0, int _flow=0, int _cap=0)
        : to(_to), flow(_flow), cap(_cap) {}
};

int L,R,m,x,y,n,S,T;
vector<vector<Muchie>> adj;
vector<int> tata;

void add_muchie(int u, int v, int cap){
    
    adj[u].push_back(Muchie(v,0,cap));
    adj[v].push_back(Muchie(u,0,0));

}

bool gaseste_lant_nesaturat(){
    queue<int> q;
    fill(tata.begin(), tata.end(), -1);

    q.push(S);
    tata[S] = S;

    while(!q.empty()){
        int nod = q.front();
        q.pop();

        for(auto& e: adj[nod]){

            if(tata[e.to] == -1 && e.cap > e.flow){
                tata[e.to] = nod;
                q.push(e.to);
                if(e.to == T)
                    return true;
            }
        }
    }
    return false;
}

int main(){

    f >> L >> R >> m;

    n = L + R;
    S = 0;
    T = n+1;


    adj.resize(T+1);
    tata.resize(T+1);

    for(int i=1; i<=m; i++){
        f >> x >> y;
        add_muchie(x,y+L, 1);
    }

    for(int i=1; i<=L; i++){
        add_muchie(S,i,1);
    }
    for(int i=1; i<=R; i++){
        add_muchie(i+L, T, 1);
    }

    int flux_maxim = 0;

    while(gaseste_lant_nesaturat()){
        
        for(int v = T; v!=S;){
            int u = tata[v];
            
            
            for(auto &e: adj[u]){
                if(e.to == v){
                    e.flow += 1;
                    break;
                }
            }
            
            
            for(auto &e: adj[v]){
                if(e.to == u){
                    e.flow -= 1;
                    break;
                }
            }
            
            v = u;
            
        }
        flux_maxim += 1;
    }

    g << flux_maxim << '\n';

    for(int i=1; i<=n; i++){
        for(auto &e: adj[i]){
            if(e.to > L && e.to <= L+R && e.flow == 1){
                g << i <<" " << e.to-L << '\n';
            }
        }
    }


    return 0;
}