Cod sursa(job #125661)

Utilizator retxedretxed retxed Data 20 ianuarie 2008 15:42:14
Problema Strazi Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.12 kb
#define DEBUG

#include <cstdio>
#include <vector>
#include <set>
#ifdef DEBUG
#include <iostream>
#endif
using namespace std;

#define NMAX 256

int N, M;
vector <int> L[NMAX];
int timp[NMAX], T=0;
bool used[NMAX], deleted[NMAX];

class cmp
{
    public:
        bool operator() (int u, int v)
        {
            return timp[u] > timp[v];
        }
};
set <int, cmp> S;

vector <int> sol;
vector < pair <int, int> > p;

void read_data()
{
    int u, v;
    scanf("%d %d", &N, &M);
    for(int i=0; i<M; ++i)
    {
        scanf("%d %d", &u, &v);
        L[u-1].push_back(v-1);
    }
}

void df_time(int v)
{
    used[v]=true;
    for(unsigned int i=0; i<L[v].size(); ++i)
        if(!used[L[v][i]])
            df_time(L[v][i]);
    timp[v]=T++;
}

void get_path(int v)
{
    int start=v, end, max=0;
    while(max!=-1)
    {
        max=-1;
        deleted[v]=true;
        sol.push_back(v);
        S.erase(v);
        for(unsigned int i=0; i<L[v].size(); ++i)
            if(!deleted[L[v][i]] && (max==-1 || timp[max]<timp[L[v][i]]))
                max=L[v][i];
        if(max!=-1)
            v=max;
    }
    end=v;
    p.push_back(make_pair(start,end));
}


int main()
{
    freopen("strazi.in", "r", stdin);
    freopen("strazi.out", "w", stdout);
    read_data();
    for(int i=0; i<N; ++i)
        used[i]=false;
    for(int i=0; i<N; ++i)
        if(!used[i])
            df_time(i);

#ifdef DEBUG
    cerr<<"Timpi: ";
    for(int i=0; i<N; ++i)
        cerr<<timp[i]<<" ";
    cerr<<endl;
#endif
    for(int i=0; i<N; ++i)
        S.insert(i);
#ifdef DEBUG
    for(set <int, cmp>::iterator it=S.begin(); it!=S.end(); ++it)
        cerr<<*it<<" ";
    cerr<<endl;
#endif

    for(int i=0; i<N; ++i)
        deleted[i]=false;
    while(!S.empty())
        get_path(*S.begin());

#ifdef DEBUG
    for(unsigned int i=0; i<p.size(); ++i)
        cerr<<"("<<p[i].first<<","<<p[i].second<<") ";
    cerr<<endl;
#endif

    printf("%d\n", p.size()-1);
    for(unsigned int i=1; i<p.size(); ++i)
        printf("%d %d\n", p[i-1].second+1, p[i].first+1);
    for(unsigned int i=0; i<sol.size(); ++i)
        printf("%d ", sol[i]+1);
    printf("\n");
    return 0;
}