Cod sursa(job #2001868)

Utilizator EuAlexOtaku Hikikomori EuAlex Data 17 iulie 2017 22:10:19
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>

using namespace std;

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

int const nmax = 10000;

int n, m, e;
int dist[1 + 2*nmax];
vector<int> g[1 + 2*nmax];
int match[1 + 2*nmax];
bool vis[1 + 2*nmax];

void bfs() {
  queue<int> q;
  for(int i = 1; i <= n + m; ++ i) {
    if(i <= n && match[i] == 0) {
      q.push(i);
      dist[i] = 0;
    } else {
      dist[i] = -1;
    }
  }


  while(!q.empty()) {
    int u1 = q.front();
    for(int i = 0; i < g[u1].size(); ++ i) {
      int v1 = g[u1][i];
      int u2 = match[v1];
      if(0 < u2 && dist[u2] < 0) {
        q.push(u2);
        dist[u2] = dist[u1] + 1;
      }
    }
    q.pop();
  }
}

bool dfs(int u1) {
  vis[u1] = 1;
  for(int i = 0; i < g[u1].size(); ++ i) {
    int v1 = g[u1][i];
    int u2 = match[v1];

    if(0 == u2) {
      match[u1] = v1;
      match[v1] = u1;
      return 1;
    } else if(vis[u2] == 0 && dist[u2] - dist[u1] == 1) {

      if(dfs(u2) == 1){
        match[u1] = v1;
        match[v1] = u1;
        return 1;
      }
    }
  }
  return 0;
}

int maxmatching() {
  int answer = 0, add = 1;
  while(0 < add) {
    bfs();
    memset(vis, 0, sizeof(vis));
    add = 0;
    for(int i=1; i<=n; i++) {
      if(match[i] == 0) {
        if(dfs(i) == 1)
          add++;
      }
    }
    answer += add;
  }
  return answer;
}

int main() {
  in >> n >> m >> e;
  for(int i = 1; i <= e; ++ i) {
    int x, y;
    in >> x >> y;
    y += n;
    g[x].push_back(y);
    g[y].push_back(x);
  }
  out << maxmatching() << '\n';
  for(int i = 1; i <= n; ++ i) {
    if(match[i] != 0)
      out << i << " " << match[i] - n << '\n';
  }
  return 0;
}