Cod sursa(job #951155)

Utilizator IoannaPandele Ioana Ioanna Data 19 mai 2013 16:36:21
Problema Cuplaj maxim in graf bipartit Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include<fstream>
#include<vector>
#include<bitset>
#define NMAX 20002

using namespace std;

int no_left_nodes,no_right_nodes,no_edges;
int match1[NMAX/2],match2[NMAX/2];
vector <int> adjacent_nodes[NMAX];
bitset <NMAX/2> visited;

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

void scan() {
  in>>no_left_nodes>>no_right_nodes>>no_edges;
  int left_node,right_node;
  for (int i = 0; i < no_edges; ++i) {
      in>>left_node>>right_node;
      adjacent_nodes[left_node].push_back(right_node);
  }
}

bool DFS(int node) {
  if (visited[node] == true) return false;
  visited[node] = true;
  for (int i = 0; i < adjacent_nodes[node].size(); ++i)
    if (match2[adjacent_nodes[node][i]] == -1) {
      match1[node] = adjacent_nodes[node][i];
      match2[adjacent_nodes[node][i]] = node;
      return true;
    }
  for (int i = 0; i < adjacent_nodes[node].size(); ++i)
    if (DFS(match2[adjacent_nodes[node][i]])) {
      match1[node] = adjacent_nodes[node][i];
      match2[adjacent_nodes[node][i]] = node;
      return true;
    }
  return false;
}

int Hopcroft_Karp() {
  bool changes;
  int edges = 0;

  for (int i = 1; i <= no_left_nodes; ++i)
    match1[i] = -1;
  for (int i = 1; i <= no_right_nodes;++i)
    match2[i] = -1;

  do {
      changes = false;
      for (int i = 1; i <= no_left_nodes; ++i)
        visited[i] = false;
      for (int i = 1; i <= no_left_nodes; ++i)
        if (match1[i] == -1)
          if (DFS(i)) {
            changes = true;
            edges++;
          }

  } while (changes == true);
  return edges;
}

int main() {
  scan();
  out<<Hopcroft_Karp()<<"\n";
  for (int i = 1; i <= no_left_nodes; ++i)
    if (match1[i] != -1)
      out<<i<<" "<<match1[i]<<endl;
  return 0;
}