Cod sursa(job #3150644)

Utilizator victorzarzuZarzu Victor victorzarzu Data 17 septembrie 2023 20:10:45
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>
#include <bitset>

using namespace std;
#define zeros(x) ((x ^ (x - 1)) & x)

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");
int n, m, e;
int l[10001], r[10001];
vector<int> graph[10001];
bool viz[10001];

void read() {
  f>>n>>m>>e;
  int x, y;
  for(int i = 1;i <= e;++i) {
    f>>x>>y;
    graph[x].push_back(y);
  }
}

bool cupl(const int& node) {
  if(viz[node]) {
    return false;
  }
  viz[node] = true;

  for(const auto& ngh : graph[node]) {
    if(!r[ngh]) {
      l[node] = ngh;
      r[ngh] = node;
      return true;
    }
  }

  for(const auto& ngh : graph[node]) {
    if(cupl(r[ngh])) {
      l[node] = ngh;
      r[ngh] = node;
      return true;
    }
  }
  return false;
}

void solve() {
  bool change = true;
  while(change) {
    change = false;
    memset(viz, false, sizeof(viz));
    for(int i = 1;i <= n;++i) {
      if(!l[i]) {
        change |= cupl(i);
      }
    }
  }
  int result = 0;
  for(int i = 1;i <= n;++i) {
    if(l[i]) {
      result++;
    }
  }
  g<<result<<'\n';

  for(int i = 1;i <= n;++i) {
    if(l[i]) {
      g<<i<<" "<<l[i]<<'\n';
    }
  }
}

int main() {
  read();
  solve();
  return 0;
}