Cod sursa(job #1165998)

Utilizator toranagahVlad Badelita toranagah Data 3 aprilie 2014 09:17:27
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <algorithm>
#include <bitset>
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int MAX_N = 10100;

int N, M, E;
vector<int> graph[MAX_N];
bitset<MAX_N> vis;
int l_pair[MAX_N];
int r_pair[MAX_N];
int match_size;

void read(), print();
void cuplaj();
bool try_match(int node);

int main() {
  read();
  cuplaj();
  print();
  return 0;
}

void read() {
  fin >> N >> M >> E;
  for (int i = 1, a, b; i <= E; i += 1) {
    fin >> a >> b;
    graph[a].push_back(b);
  }
}

void cuplaj() {
  bool go = 1;
  while (go) {
    go = 0;
    vis = 0;
    for (int i = 1; i <= N; i += 1)
      if (!l_pair[i] && try_match(i))
        match_size += 1, go = 1;
  }
}

bool try_match(int node) {
  if (vis[node]) return 0;
  vis[node] = 1;

  for (auto x: graph[node]) {
    if (!r_pair[x] || try_match(r_pair[x])) {
      l_pair[node] = x;
      r_pair[x] = node;
      return 1;
    }
  }
  return 0;
}

void print() {
  fout << match_size << '\n';
  for (int i = 1; i <= N; i += 1) {
    if (r_pair[l_pair[i]] == i)
      fout << i << ' ' << l_pair[i] << '\n';
  }
}