Cod sursa(job #2219563)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 9 iulie 2018 12:53:25
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
/**
  *  Worg
  */
#include <cstdio>
#include <vector>

FILE *fin = freopen("cuplaj.in", "r", stdin); FILE *fout = freopen("cuplaj.out", "w", stdout);

const int MAX_N = 1e4 + 5;

/*-------- Data --------*/
int n, m, e;
std::vector<std::vector<int > > graph;

int matchCount;
int checked[MAX_N], left[MAX_N], right[MAX_N];
/*-------- --------*/

void ReadInput() {
  scanf("%d%d%d", &n, &m, &e); graph.resize(n + 1);

  for(int i = 0; i < e; i++) {
    int nodeLeft, nodeRight; scanf("%d%d", &nodeLeft, &nodeRight);

    graph[nodeLeft].push_back(nodeRight);
  }
}

bool PairUp(int node) {
  if(checked[node]) return false;
  checked[node] = true;

  //  Check if the current node has an adjacent unmatched node
  for(auto& nxt : graph[node]) {
    if(!right[nxt]) {
      left[node] = nxt; right[nxt] = node;
      matchCount++;

      return true;
    }
  }

  //  Check further
  for(auto& nxt : graph[node]) {
    if(PairUp(right[nxt])) {
      left[node] = nxt; right[nxt] = node;

      return true;
    }
  }

  return false;
}

void HopcroftKarp() {
  bool ok;
  do {
    for(int i = 1; i <= n; i++) {
      checked[i] = false;
    }

    ok = false;
    for(int i = 1; i <= n; i++) {
      if(!left[i]) {
        ok |= PairUp(i);
      }
    }
  }while(ok);
}

void WriteOutput() {
  printf("%d\n", matchCount);
  for(int i = 1; i <= n; i++) {
    if(left[i]) {
      printf("%d %d\n", i, left[i]);
    }
  }
}

int main() {
  ReadInput();

  HopcroftKarp();

  WriteOutput();

  return 0;
}