Cod sursa(job #986399)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 18 august 2013 17:42:21
Problema Strazi Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.55 kb
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#include <algorithm>
#include <utility>
#include <cstring>
#include <string>
#include <stack>
#include <deque>
#include <iomanip>
#include <set>
#include <map>
#include <cassert>
#include <ctime>
#include <list>
#include <iomanip>

using namespace std;

ifstream cin("strazi.in");
ofstream cout("strazi.out");

const int MAXN = 305;
const int oo = (1<<31)-1;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

struct ClassComp {
    inline bool operator () (const int &a, const int &b) const {
        return a > b;
    }
};

Graph G;
int N, M, Pair[MAXN], Cuplaj[MAXN];
vector<int> X, Y(MAXN);
bitset<MAXN> Used;

inline bool PairUp(int Node) {
    if(Used[Node])
        return false;
    Used[Node] = true;
    for(It it = G[Node].begin(), fin = G[Node].end() ; it != fin ; ++ it)
        if(!Pair[*it]) {
            Cuplaj[Node] = *it;
            Pair[*it] = Node;
            return true;
        }
    for(It it = G[Node].begin(), fin = G[Node].end() ; it != fin ; ++ it)
        if(PairUp(Pair[*it])) {
            Cuplaj[Node] = *it;
            Pair[*it] = Node;
            return true;
        }
    return false;
}

inline int DFs(int Node) {
    if(!Pair[Node])
        return Node;
    return DFs(Pair[Node]);
}

inline void PrintDFs(int Node) {
    if(!Node)
        return;
    cout << Node << ' ';
    PrintDFs(Pair[Node]);
}

int main() {
    cin >> N >> M;
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        cin >> x >> y;
        G[y].push_back(x);
    }
    for( bool ok = true ; ok ; ) {
        ok = false;
        Used.reset();
        for(int i = 1 ; i <= N ; ++ i)
            if(!Cuplaj[i])
                ok |= PairUp(i);
    }
    for(int i = 1 ; i <= N ; ++ i)
        if(!Cuplaj[i]) {
            X.push_back(i);
            Y[i] = DFs(i);
        }
    cout << X.size() - 1 << '\n';
    for(int i = 0 ; i < X.size() - 1 ; ++ i)
        Pair[Y[X[i]]] = X[i + 1];
    for(int i = 0 ; i < X.size() - 1 ; ++ i)
        cout << Y[X[i]] << ' ' << X[i+1] << '\n';
    PrintDFs(X[0]);
    cout << "\n";
    cin.close();
    cout.close();
    return 0;
}