Cod sursa(job #3268942)

Utilizator EnnBruhEne Andrei EnnBruh Data 18 ianuarie 2025 09:46:21
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>
#define endl '\n'

using namespace std;

const string fileName = "cuplaj";
ifstream in  (fileName + ".in");
ofstream out (fileName + ".out");

const int maxSize = 10002;
const int inf = 0x3f3f3f3f;

vector <int> adj[maxSize];
bitset <maxSize> visited;
int leftMatch[maxSize], rightMatch[maxSize];
vector <pair <int , int>> toShow;

bool kuhn(int node) {
    if (visited[node]) return false;
    visited[node] = true;

    for (auto next : adj[node])
        if (!rightMatch[next] || kuhn(rightMatch[next])) {
            rightMatch[next] = node; leftMatch[node] = next;
            return true;
        }

    return false;
}

int main( ) {
    int left, right, numEdges;
    in >> left >> right >> numEdges;

    int nodeA, nodeB;
    for (int i = 1; i <= numEdges; ++i) {
        in >> nodeA >> nodeB;
        adj[nodeA].push_back( nodeB );
    }

    bool change = true;
    while (change) {
        change = false;
        visited = 0;
        for (int node = 1; node <= left; ++node)
            if (!leftMatch[node]) change |= kuhn( node );
    }

    for (int node = 1; node <= right; ++node)
        if (rightMatch[node]) toShow.push_back({rightMatch[node], node});

    sort(toShow.begin( ), toShow.end( ));

    out << toShow.size( ) << endl;
    for (auto elem : toShow) out << elem.first << ' ' << elem.second << endl;

    return 0;
}