Cod sursa(job #3216731)

Utilizator LuciBBadea Lucian LuciB Data 19 martie 2024 14:33:06
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e4;

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

vector<int> graph[NMAX];

int leftNode[NMAX], rightNode[NMAX];
bool vis[NMAX];

bool pairUp(int node) {
    if(vis[node])
        return false;
    vis[node] = true;
    for(auto x : graph[node]) {
        if(rightNode[x] == -1) {
            leftNode[node] = x;
            rightNode[x] = node;
            return true;
        }
    }
    for(auto x : graph[node]) {
        if(pairUp(rightNode[x])) {
            leftNode[node] = x;
            rightNode[x] = node;
            return true;
        }
    }
    return false;
}

int main(){
    int n, m, e;
    fin >> n >> m >> e;
    while(e--) {
        int x, y;
        fin >> x >> y;
        x--, y--;
        graph[x].push_back(y);
    }
    for(int i = 0; i < n; i++)
        leftNode[i] = -1, vis[i] = false;
    for(int i = 0; i < m; i++)
        rightNode[i] = -1;
    bool notOk = true;
    while(notOk) {
        notOk = false;
        for(int i = 0; i < n; i++)
            vis[i] = false;
        for(int i = 0; i < n; i++)
            if(leftNode[i] == -1)
                notOk |= pairUp(i);
    }
    int cuplaj = 0;
    for(int i = 0; i < n; i++)
        if(leftNode[i] != -1)
            cuplaj++;
    fout << cuplaj << endl;
    for(int i = 0; i < n; i++)
        if(leftNode[i] != -1)
            fout << i + 1 << ' ' << leftNode[i] + 1 << endl;
    return 0;
}