Cod sursa(job #2949949)

Utilizator andreic06Andrei Calota andreic06 Data 2 decembrie 2022 13:25:25
Problema Cuplaj maxim in graf bipartit Scor 18
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <bits/stdc++.h>

using namespace std;
const int NMAX = 1e4;
const int MMAX = 1e4;
const int NONE = -1;

int N, M, E; vector<int> g[1 + NMAX];

bool visited[1 + NMAX];
int match[1 + MMAX]; /// match[v] = u, v in B, u in A

bool getPath (int root) {
   if (visited[root])
     return false;

   visited[root] = true;
   for (int node : g[root]) {
      if (match[node] == NONE || getPath (match[node])) {
        match[node] = root;
        return true;
      }
   }
   return false;
}

int main()
{
   ifstream in ("cuplaj.in");
   in >> N >> M >> E;
   for (int i = 1; i <= E; i ++) {
      int u, v; in >> u >> v;
      g[u].push_back (v);
   }

   for (int node = 1; node <= M; node ++)
      match[node] = NONE;

   bool found_match;
   do {
     found_match = false;
     for (int node = 1; node <= N; node ++)
        if (getPath (node))
          found_match = true;
     for (int node = 1; node <= N; node ++)
        visited[node] = false;
   }while (found_match);

   int answer = 0;
   for (int node = 1; node <= M; node ++) {
      if (match[node] != NONE)
        answer ++;
   }

   ofstream out ("cuplaj.out");
   out << answer << "\n";
   for (int node = 1; node <= M; node ++)
      if (match[node] != NONE)
        out << match[node] << " " << node << "\n";
    return 0;
}