Cod sursa(job #1580273)

Utilizator vladrochianVlad Rochian vladrochian Data 25 ianuarie 2016 18:50:43
Problema Strazi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.51 kb
#include <cstring>
#include <fstream>
#include <vector>

using namespace std;

const int N_MAX = 255;

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

int N, M;
vector<int> G[N_MAX + 5];

int l[N_MAX + 5], r[N_MAX + 5];
bool use[N_MAX + 5];

int cnt;
vector<int> path;

inline void Link(int x, int y) {
   l[x] = y;
   r[y] = x;
}

bool PairUp(int node) {
   if (use[node])
      return false;
   use[node] = true;

   for (int i : G[node])
      if (!r[i]) {
         Link(node, i);
         return true;
      }

   for (int i : G[node])
      if (PairUp(r[i])) {
         Link(node, i);
         return true;
      }

   return false;
}

void Match() {
   bool ok = true;
   while (ok) {
      ok = false;
      memset(use, 0, sizeof use);
      for (int i = 1; i <= N; ++i)
         if (!l[i])
            ok |= PairUp(i);
   }
}

int main() {
   fin >> N >> M;
   while (M--) {
      int x, y;
      fin >> x >> y;
      G[x].push_back(y);
   }

   Match();

   for (int i = 1; i <= N; ++i)
      cnt += !l[i];
   fout << cnt - 1 << "\n";

   memset(use, 0, sizeof use);
   for (int i = 1, last = 0; i <= N; ++i)
      if (!r[i]) {
         if (last)
            fout << last << " " << i << "\n";
         path.push_back(i);
         int j = i;
         while (l[j]) {
            j = l[j];
            path.push_back(j);
         }
         last = j;
      }

   for (int i : path)
      fout << i << " ";
   fout << "\n";
   return 0;
}