Cod sursa(job #3270981)

Utilizator AlexandruBenescuAlexandru Benescu AlexandruBenescu Data 24 ianuarie 2025 23:05:34
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
#define L 10005
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

int n, m, e;
int le[L], ri[L];
vector <int> G[L];
bool vis[L];

bool pairup(int node) {
  if (vis[node])
    return false;
  vis[node] = true;

  for (auto it : G[node]) {
    if (ri[it] == 0) {
      le[node] = it;
      ri[it] = node;
      return true;
    }
  }

  for (auto it : G[node]) {
    if (pairup(ri[it])) {
      le[node] = it;
      ri[it] = node;
      return true;
    }
  }

  return false;
}

int main() {
  fin >> n >> m >> e;
  for (int i = 1; i <= e; i++) {
    int a, b;
    fin >> a >> b;
    G[a].push_back(b);
  }

  bool ok = true;
  while (ok) {
    ok = false;
    for (int i = 1; i <= n; i++)
      vis[i] = false;
    for (int i = 1; i <= n; i++)
      if (le[i] == 0 && pairup(i))
        ok = true;
  }

  int cnt = 0;
  for (int i = 1; i <= n; i++)
    cnt += (bool)le[i];
  fout << cnt << "\n";
  for (int i = 1; i <= n; i++)
    if (le[i])
      fout << i << " " << le[i] << "\n";
  return 0;
}