Cod sursa(job #2863050)

Utilizator NanuGrancea Alexandru Nanu Data 6 martie 2022 11:57:26
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#include <vector>

using namespace std;

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

//un nod din A grupat cu un nod din B se descupleaza
//doar daca nodul din are mai are un nod liber in B cu care se poate cupla;

#define DIM 10000

bool sel[DIM + 1];
int n, m, e;
int st[DIM + 1];  //cu ce nod grupez nodul din stanga;
int dr[DIM + 1];  //cu ce nod e grupat nodul din dreapta;
vector <int> G[DIM + 1];

static inline bool Cupleaza(int nod) {
  if(sel[nod])
    return 0;

  sel[nod] = 1;
  for(auto e : G[nod])
    if(!dr[e] || Cupleaza(dr[e])) { //daca e liber sau daca poate fi cuplat cu alt nod;
      st[nod] = e;
      dr[e] = nod;
      return 1;
    }

  return 0;
}

int main() {
  fin >> n >> m >> e;
  for(int i = 1; i <= e; i++) {
    int x, y;

    fin >> x >> y;
    G[x].push_back(y);
  }

  bool found = 1;
  while(found) {                //cat timp gasesc noduri bune de cuplat;
    for(int i = 1; i <= n; i++) //resetez nodurile vizitate;
      sel[i] = 0;
    found = 0;

    for(int i = 1; i <= n; i++) 
      if(!st[i] && Cupleaza(i)) //daca nodul i nu e cuplat dar am gasit cu cine sa l cuplez;
        found = 1;
  }

  int cuplaje = 0;
  for(int i = 1; i <= n; i++)
    cuplaje += (st[i] != 0);

  fout << cuplaje << '\n';
  for(int i = 1; i <= n; i++)
    if(st[i])
      fout << i << " " << st[i] << '\n';

  return 0;
}