Cod sursa(job #2816902)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 12 decembrie 2021 14:14:43
Problema Cuplaj maxim in graf bipartit Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#define d(x) std::cout << x << std::endl
#define dm(msg, x) std::cout << msg << x << std::endl

#define all(a) a.begin(), a.end()
#define range(a, l, r) a.begin() + l, a.begin() + r
#define aall(a, n) a + 1, a + 1 + n
#define arange(a, l, r) a + l, a + r
	
#define maxself(a, b) a = std::max(a, b);
#define minself(a, b) a = std::min(a, b);

#define inout(f) std::ifstream in((f) + (std::string) ".in");std::ofstream out((f) + (std::string) ".out")

#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

const int NMAX = 1e5;

int n, m, e;

std::vector<int> gLeft[1 + NMAX];
std::vector<int> gRight[1 + NMAX];

int matchLeft[1 + NMAX];
int matchRight[1 + NMAX];

bool vis[1 + NMAX];

bool match(int i) {
  if (vis[i])
    return false;
  
  vis[i] = true;

  for (int j : gLeft[i]) {
    if (matchRight[j] == 0) {
      matchLeft[i] = j;
      matchRight[j] = i;

      return true;
    }
  }

  for (int j : gLeft[i]) {
    if (match(matchRight[j])) {
      matchLeft[i] = j;
      matchRight[j] = i;

      return true;
    }
  }

  return false;
}

int main() {
  inout("cuplaj");

  in >> n >> m >> e;

  while (e--) {
    int a, b;
    in >> a >> b;

    gRight[a].push_back(b);
    gLeft[b].push_back(a);
  }

  bool ok = true;
  while (ok) {
    memset(vis, 0, sizeof(vis));
    ok = false;

    for (int i = 1; i <= n; ++i)
      if (matchLeft[i] == 0)
        ok |= match(i);
  }

  int cnt = 0;
  for (int i = 1; i <= n; ++i) {
    if (matchRight[i] != 0)
      ++cnt;
  }
  out << cnt << '\n';

  for (int i = 1; i <= n; ++i) {
    if (matchRight[i] != 0)
      out << i << ' ' << matchRight[i] << '\n';
  }

  return 0;
}