Cod sursa(job #886238)

Utilizator sebii_cSebastian Claici sebii_c Data 22 februarie 2013 18:46:49
Problema Felinare Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.75 kb
#include <cstdio>
#include <cstring>

#include <vector>

using namespace std;

typedef vector<int>::iterator iter;

const int MAXN = 16400;

vector<int> G[MAXN];

int l[MAXN];
int r[MAXN];
bool vis[MAXN];
bool visleft[MAXN];
bool visright[MAXN];

int pair_up(int node)
{
    if (vis[node])
        return 0;
    vis[node] = true;

    for (iter it = G[node].begin(); it != G[node].end(); ++it) {
        if (!r[*it]) {
            r[*it] = node;
            l[node] = *it;
            visleft[node] = true;
            return 1;
        }
    }
    for (iter it = G[node].begin(); it != G[node].end(); ++it) {
        if (pair_up(r[*it])) {
            r[*it] = node;
            l[node] = *it;
            visleft[node] = true;
            return 1;
        }
    }
    return 0;
}

void doit(int node)
{
    for (iter it = G[node].begin(); it != G[node].end(); ++it)
        if (!visright[*it]) {
            visright[*it] = true;
            visleft[l[*it]] = false;
            doit(l[*it]);
        }
}

int main()
{
    freopen("felinare.in", "r", stdin);
    freopen("felinare.out", "w", stdout);

    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 0; i < m; ++i) {
        int x, y;
        scanf("%d %d", &x, &y);
        G[x].push_back(y);
    }

    for (int poss = 1; poss != 0; ) {
        poss = 0;
        memset(vis, false, sizeof(vis));
        for (int i = 1; i <= n; ++i) 
            if (!l[i]) 
                poss |= pair_up(i);
    }

    int coupling = 0;
    for (int i = 1; i <= n; ++i)
        if (l[i] != 0) ++coupling;

    printf("%d\n", 2 * n - coupling);

    for (int i = 1; i <= n; ++i)
        if (!visleft[i])
            doit(i);
    for (int i = 1; i <= n; ++i)
        printf("%d\n", visleft[i] ^ 1 + 2 * (visright[i] ^ 1));

    return 0;
}