Cod sursa(job #1401976)

Utilizator maribMarilena Bescuca marib Data 26 martie 2015 11:26:52
Problema Felinare Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.8 kb
#include <fstream>
#include <vector>
#include <cstring>
#define DIM 9000
using namespace std;

ifstream in("felinare.in");
ofstream out("felinare.out");

int felinare, n, m, first[DIM], second[DIM], r_match[DIM], l_match[DIM], vis[DIM];

vector <int> edges[DIM];

bool cupleaza(int nod){
    int neigh;
    if(vis[nod]) return false;
    vis[nod]=1;
    for(int i=0; i<edges[nod].size(); ++i){
        neigh=edges[nod][i];
        if(!r_match[neigh]){
            r_match[neigh]=nod;
            l_match[nod]=neigh;
            return true;
        }
    }
    for(int i=0; i<edges[nod].size(); ++i){
        neigh=edges[nod][i];
        if(cupleaza(r_match[neigh])){
            r_match[neigh]=nod;
            l_match[nod]=neigh;
            return true;
        }
    }
    return false;
}

void build_matching(){
    int temp=1;
    while(temp){
        temp=0;
        memset(vis, 0, sizeof(vis));
        for(int i=1; i<=n; ++i){
            if(!l_match[i]&&cupleaza(i)){
                temp=1;
            }
        }
    }
}

void solve(){
    int neigh;
    for(int i=1; i<=n; ++i){
        if(l_match[i]){
            felinare--;
            neigh=l_match[i];
            if(first[i]>second[neigh])
                first[i]=-1;
            else
                second[neigh]=-1;
        }
    }
}

int main()
{
    int a, b;
    in>>n>>m;
    while(m--){
        in>>a>>b;
        first[a]++;
        second[b]++;
        edges[a].push_back(b);
    }
    build_matching();
    felinare=2*n;
    solve();
    out<<felinare<<"\n";
    for(int i=1; i<=n; ++i){
        if(first[i]==-1&&second[i]==-1)
            out<<"0\n";
        if(first[i]==-1&&second[i]>=0)
            out<<"2\n";
        if(first[i]>=0&&second[i]==-1)
            out<<"1\n";
        if(first[i]>=0&&second[i]>=0)
            out<<"3\n";
    }
    return 0;
}