Cod sursa(job #3257708)

Utilizator MikeStrikeAgache Mihai MikeStrike Data 18 noiembrie 2024 22:53:47
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring> 

using namespace std;

const int MAXN = 10005;
 
vector<int> G[MAXN];  
int l[MAXN], r[MAXN], u[MAXN]; 
 
int pairup(const int n) {
    if (u[n]) return 0; 
    u[n] = 1; 
    for (int neighbor : G[n]) {
        if (!r[neighbor]) { 
            l[n] = neighbor;
            r[neighbor] = n;
            return 1; 
        }
    }
    for (int neighbor : G[n]) {
        if (pairup(r[neighbor])) {
            l[n] = neighbor;
            r[neighbor] = n;
            return 1; 
        }
    }
    return 0;  
}

int main() {
    ifstream in("cuplaj.in");
    ofstream out("cuplaj.out");

    int n, m, cnt_edges;
    
    in>>n>>m>>cnt_edges;

    while (cnt_edges--) {
        int x, y;
        in>>x>>y;  
        G[x].push_back(y);
    }

    for (int change = 1; change;) {
        change = 0;
        memset(u, 0, sizeof(u));
        for (int i = 1; i <= n; ++i) {
            if (!l[i]) { 
                change |= pairup(i);  
            }
        }
    }

    int cuplaj = 0;
    for (int i = 1; i <= n; ++i) {
        if (l[i] > 0) cuplaj++;
    }

    out<< cuplaj<< "\n";  
    for (int i = 1; i <= n; ++i) {
        if (l[i] > 0) out<< i<<' '<< l[i]<<'\n';      
    }

    return 0;
}