Cod sursa(job #2556910)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 25 februarie 2020 12:08:53
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 1e4 + 5;

int ans[nmax];
bool viz[nmax];
int matched[nmax];
vector <int> neigh[nmax];

int canMatch(int node)
{
    viz[node] = 1;
    for (auto next: neigh[node])
        if (!matched[next])
        {
            matched[next] = node;
            ans[node] = next;
            return 1;
        }
        else if (!viz[matched[next]] && canMatch(matched[next]))
        {
            ans[node] = next;
            matched[next] = node;
            return 1;
        }
    return 0;
}

int main()
{
    int n, m, e;
    f >> n >> m >> e;
    for (int i = 1; i <= e; ++ i)
    {
        int u, v;
        f >> u >> v;
        neigh[u].push_back(v);
    }
    int cnt = 1;
    while (cnt)
    {
        cnt = 0;
        for (int node = 1; node <= n; ++ node)
            viz[node] = 0;
        for (int node = 1; node <= n; ++ node)
            if (!ans[node] && !viz[node])
                cnt |= canMatch(node);
    }
    int all = 0;
    for (int node = 1; node <= n; ++ node)
        if (ans[node])
            all ++;
    g << all << '\n';
    for (int node = 1; node <= n; ++ node)
        if (ans[node])
            g << node << " " << ans[node] << '\n';
}