Cod sursa(job #557548)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 16 martie 2011 18:23:46
Problema Sortare topologica Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include<cstdio>
#define Nmx 1000001

using namespace std;

int viz[Nmx],n,m,pre[Nmx],nr;
struct nod
{
    int inf;
    nod *urm;
};
nod *G[Nmx];

void add(int x,int y)
{
    nod *aux=new nod;
    aux->inf = y;
    aux->urm = G[x];
    G[x] = aux;
}

void citire()
{
    int x,y;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d",&x,&y);
        add(x,y);
    }
}

void dfs(int x)
{
    viz[x]=1;
    for(nod *p=G[x];p;p=p->urm)
        if(!viz[p->inf])
            dfs(p->inf);
    pre[++nr]=x;
}

int main()
{
    freopen("sortaret.in","r",stdin);
    freopen("sortaret.out","w",stdout);
    citire();
    for(int i=1;i<=n;++i)
        if(!viz[i])
            dfs(i);
    for(int i=n;i>=1;--i)
        printf("%d ",pre[i]);
    return 0;
}