Cod sursa(job #3306046)

Utilizator andrei.nNemtisor Andrei andrei.n Data 6 august 2025 21:58:47
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>

using namespace std;

vector<int> v[10005];
int to[10005];
int from[10005];
int use[10005];

bool dfs(int node)
{
    if(use[node]) return false;
    use[node] = 1;
    int val = to[node];
    for(auto oth : v[node])
    {
        to[node] = oth;
        if(!from[oth])
        {
            from[oth] = node;
            return true;
        }
    }
    for(auto oth : v[node])
    {
        to[node] = oth;
        if(dfs(from[oth]))
        {
            from[oth] = node;
            return true;
        }
    }
    to[node] = val;
    return false;
}

int main()
{
    ifstream fin ("cuplaj.in");
    ofstream fout ("cuplaj.out");
    ios::sync_with_stdio(false); fin.tie(0); fout.tie(0);
    int n, m, e; fin>>n>>m>>e;
    while(e--)
    {
        int a, b; fin>>a>>b;
        v[a].push_back(b);
    }
    int ok = 0;
    while(!ok)
    {
        ok = 1;
        for(int i=1; i<=n; ++i)
            use[i] = 0;
        for(int i=1; i<=n; ++i)
            if(!to[i])
                if(dfs(i))
                    ok = 0;
    }
    int cnt=0;
    for(int i=1; i<=n; ++i)
        if(to[i])
            ++cnt;
    fout<<cnt<<'\n';
    for(int i=1; i<=n; ++i)
        if(to[i])
            fout<<i<<' '<<to[i]<<'\n';
    return 0;
}