Cod sursa(job #2020434)

Utilizator AlexandruLuchianov1Alex Luchianov AlexandruLuchianov1 Data 10 septembrie 2017 11:52:41
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
int const nmax = 10000;

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

void bfs() {
  queue<int> q;
  for(int i = 1; i <= n; i++){
    if(match[i] == 0){
      q.push(i);
      dist[i] = 0;
    } else
      dist[i] = -1;
  }
  while(0 < q.size() ){
    int u1 = q.front(); //node e foarte bine pentru flux. Pentru cuplaj e si mai bine u1
    q.pop();

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

int 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(u2 == 0) {
      match[v1] = u1;
      match[u1] = v1;
      return 1;
    } else if(dist[u1] + 1 == dist[u2]) {
      if(dfs(u2) == 1) {
        match[v1] = u1;
        match[u1] = v1;
        return 1;
      }
    }
  }
  return 0;
}

int maxmatch() {
  int flag = 1, answer = 0;
  while(flag == 1) {
    flag = 0;
    bfs();
    for(int i = 1 ; i <= n ;i++){
      vis[i] = 0;
    }

    for(int i = 1  ; i <= n ;i++){
      if(match[i] == 0){
        if(dfs(i) == 1){
          answer++;
          flag = 1;
        }
      }
    }
  }
  return answer;
}

int main(){
  in >> n >> m >> e;

  int a , b;
  for(int i = 1 ; i <= e ;i++){
    in>>a>>b;
    b += n;
    g[a].push_back(b);
    g[b].push_back(a);
  }
  out<<maxmatch()<<'\n';
  for(int i = 1 ; i <= n ;i++){
    if(0 < match[i] - n)
      out<<i<<" "<<match[i] - n<<'\n';
  }
}