Cod sursa(job #3329881)

Utilizator mirudragunoiDragunoi Miruna mirudragunoi Data 16 decembrie 2025 12:44:53
Problema Cuplaj maxim in graf bipartit Scor 8
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1e4 + 10;
int capacitate[NMAX + 1][NMAX + 1], flux[NMAX + 1][NMAX + 1];
int vis[NMAX + 1], p[NMAX + 1];
vector<int> G[NMAX + 1];
int n, m, e;

int bfs(int s, int d) {
  for(int i = 0; i <= n + m + 1; i++) {
    vis[i] = 0;
    p[i] = 0;
  }
  queue<int> q;
  q.push(s);
  vis[s] = 1;
  while(!q.empty()) {
    int nod = q.front();
    q.pop();
    for(auto vecin : G[nod]) {
      if(!vis[vecin] && capacitate[nod][vecin] - flux[nod][vecin] > 0) {
        vis[vecin] = 1;
        q.push(vecin);
        p[vecin] = nod;
      }
    }
  }
  if(vis[d] == 0) {
    return 0;
  }
  vector<int> path;
  int curr = d;
  while(curr != 0) {
    path.push_back(curr);
    curr = p[curr];
  }
  reverse(path.begin(), path.end());
  int flow = 1e9;
  for(int i = 0; i < path.size() - 1; i++) {
    int x = path[i];
    int y = path[i + 1];
    flow = min(flow, capacitate[x][y] - flux[x][y]);
  }
  for(int i = 0; i < path.size() - 1; i++) {
    int x = path[i];
    int y = path[i + 1];
    flux[x][y] += flow;
    flux[y][x] -= flow;
  }
  return flow;
}

int main() {
  ifstream cin("cuplaj.in");
  ofstream cout("cuplaj.out");

  cin >> n >> m >> e;

  int sursa = 0;
  int dest = n + m + 1;

  // conectez sursa la toate nodurile din L cu capacitate 1
  for(int i = 1; i <= n; i++) {
    capacitate[sursa][i] = 1;
    G[sursa].push_back(i);
    G[i].push_back(sursa);
  }

  // conectez toate nodurile din R la destinatie cu capacitate 1
  for(int i = 1; i <= m; i++) {
    int nod_r = n + i;
    capacitate[nod_r][dest] = 1;
    G[nod_r].push_back(dest);
    G[dest].push_back(nod_r);
  }

  for(int i = 0; i < e; i++) {
    int u, v;
    cin >> u >> v;
    int nod_r = n + v;
    capacitate[u][nod_r] = 1;
    G[u].push_back(nod_r);
    G[nod_r].push_back(u);
  }

  int maxflow = 0;
  while(true) {
    int flow = bfs(sursa, dest);
    if(flow == 0) {
      break;
    }
    maxflow += flow;
  }

  cout << maxflow << "\n";

  for(int i = 1; i <= n; i++) {
    for(int j = 1; j <= m; j++) {
      int nod_r = n + j;
      if(flux[i][nod_r] == 1) {
        cout << i << " " << j << "\n";
      }
    }
  }
  return 0;
}