Cod sursa(job #3226709)

Utilizator MoolampMorosan Teodor Moolamp Data 22 aprilie 2024 17:12:29
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;
const int NMAX = 1e4 + 5;

bool viz[NMAX], used[NMAX], ok, sw;
int n, m, e, mt[NMAX], init[NMAX];
vector<int> v[NMAX];

bool kuhn (int x)
{
  viz[x] = true;
  for (auto u : v[x])
    if (!mt[u] || (!viz[mt[u]] && kuhn(mt[u])))
    {
      mt[u] = x;
      used[x] = true;
      return true;
    }
  return false;
}

signed main ()
{
  freopen("cuplaj.in", "r", stdin);
  freopen("cuplaj.out", "w", stdout);
  cin.tie(nullptr)->sync_with_stdio(false);
  cin >> n >> m >> e;
  if (n > m)
  {
    swap(n, m);
    sw = true;
  }
  while (e--)
  {
    int x, y; cin >> x >> y;
    if (sw)
      swap(x, y);
    v[x].push_back(y);
  }
  for (int i = 1; i <= n; i++)
    init[i] = i;
  sort(init + 1, init + n + 1, [&] (int x, int y)
  {
    return v[x].size() < v[y].size();
  });
  for (int i = 1; i <= n; i++)
    for (auto x : v[i])
      if (!mt[x])
      {
        used[i] = true;
        mt[x] = i;
        break;
      }
  do
  {
    ok = false;
    for (int i = 1; i <= n; i++)
      if (!viz[i] && !used[i])
        ok |= kuhn(i);
    memset(viz, false, sizeof(viz));
  } while (ok);
  cout << m - count(mt + 1, mt + m + 1, 0) << '\n';
  for (int i = 1; i <= m; i++)
    if (mt[i])
    {
      if (sw)
        cout << i << ' ' << mt[i] << '\n';
      else
        cout << mt[i] << ' ' << i << '\n';
    }
}