Nu aveti permisiuni pentru a descarca fisierul grader_test4.in

Cod sursa(job #951157)

Utilizator IoannaPandele Ioana Ioanna Data 19 mai 2013 16:41:32
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include<fstream>
#include<vector>
#include<bitset>
#define NMAX 20002
#define NNMAX 10002
using namespace std;

int no_left_nodes,no_right_nodes,no_edges;
int match1[NNMAX],match2[NNMAX];
vector <int> adjacent_nodes[NMAX];
bitset <NNMAX> 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) {
  int limit;
  int next_node;
  if (visited[node] == true) return false;
  visited[node] = true;
  limit = adjacent_nodes[node].size();

  for (int i = 0; i < limit; ++i) {
    next_node = adjacent_nodes[node][i];
    if (match2[next_node] == -1) {
      match1[node] = next_node;
      match2[next_node] = node;
      return true;
    }
  }
  for (int i = 0; i < limit; ++i) {
    next_node = adjacent_nodes[node][i];
    if (DFS(match2[adjacent_nodes[node][i]])) {
      match1[node] = next_node;
      match2[next_node] = 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;
}