//edited by Eddy
//from BUAA SoftWare College
//any question:oeddyo@gmail.com
//先建圖,DFS找F[U],再把F[U]從大到小排序即可
#define MAX 105
#define NIL 1000000
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct edge

{
int adjvex;
struct edge *next;
}ELink;
typedef struct ver

{
int number; //存入度
int vertex; //頂點(diǎn)信息
struct edge *link;
bool flag;
}VLink;
int mytime;
VLink G[MAX]; //G作為全局,免去過多參數(shù)傳遞
int color[MAX];
int f[MAX];
int a[MAX];
void Creat(int N) //n為頂點(diǎn)數(shù),e為邊數(shù)

{
for(int k=1;k<=N;k++) //注意,0沒有用
{
G[k].vertex=k;
G[k].link=NULL;
}
for(int i=1;i<=N;i++)
{
int j=0;
int temp;
cin>>temp;
while(temp!=0)
{
a[j++]=temp;
cin>>temp;
}
int k,vi,vj,weight;
ELink *p,*q;
for(k=0;k<j;k++)
{
int temp=a[k];
G[a[k]].number++;
p=new ELink;
p->adjvex=temp;
p->next=NULL;
if(!G[i].link)
{
G[i].link=p;
}
else
{
q=G[i].link;
while(q->next)
{
q=q->next;
}
q->next=p;
}
G[i].flag=0; //未被刪
}
}
}
void TopSort(int N)

{
int remains=N;
while(remains>0)
{
for(int i=1;i<=N;i++)
{
if(G[i].flag==1)
continue;
if(G[i].number==0) //入度為0,刪掉
{
G[i].flag=1;
ELink *p=G[i].link;
while(p)
{
G[p->adjvex].number--;
p=p->next;
}
remains--;
if(remains>0)
cout<<G[i].vertex<<" ";
else
cout<<G[i].vertex<<endl;
}
}
}
}

int main()

{
int N; //1~100
cin>>N;
Creat(N);

TopSort(N);return 0;
}
沒啥多說的,裸拓排
用了算導(dǎo)上的求f[u]的算法
以下是AC代碼:
用刪除入度為0的方法做了次,時間短了一半。
//edited by Eddy
//from BUAA SoftWare College
//any question:oeddyo@gmail.com
#define MAX 105
#define NIL 1000000
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct edge

{
int adjvex;
int weight;
struct edge *next;
}ELink;
typedef struct ver

{
int vertex; //頂點(diǎn)信息
struct edge *link;
}VLink;
int mytime;
VLink G[MAX]; //G作為全局,免去過多參數(shù)傳遞
int color[MAX];
int f[MAX];
int a[MAX];
void Creat(int N) //n為頂點(diǎn)數(shù),e為邊數(shù)

{
for(int k=1;k<=N;k++) //注意,0沒有用
{
G[k].vertex=k;
G[k].link=NULL;
}
for(int i=1;i<=N;i++)
{
int j=0;
int temp;
cin>>temp;
while(temp!=0)
{
a[j++]=temp;
cin>>temp;
}
int k,vi,vj,weight;
ELink *p,*q;
for(k=0;k<j;k++)
{
int temp=a[k];
p=new ELink;
p->adjvex=temp;
p->next=NULL;
if(!G[i].link)
{
G[i].link=p;
}
else
{
q=G[i].link;
while(q->next)
{
q=q->next;
}
q->next=p;
}
}
}
}
void DFS_visit(int u)

{
color[u]=2;
mytime++;
ELink *p;
p=G[u].link;
int v=0;
while(p)
{
v++;
if(color[G[p->adjvex].vertex]==1)
{
DFS_visit(p->adjvex);
}
p=p->next;
}
color[u]=3;
f[u]=++mytime;
}
void DFS(int N) //N為頂點(diǎn)數(shù)

{
for(int i=1;i<=N;i++)
{
color[i]=1; //1:white 2:grey 3:black
}
mytime=0;
for(int i=1;i<=N;i++)
{
if(color[i]==1)
{
DFS_visit(i);
}
}
}


void mysort(int N)

{
int i,j,flag=1;
for(i=1;i<=N;i++)
{
a[i]=i;
}
int temp;
i=N-1;
while(i>0&&flag==1)
{
flag=0;
for(j=1;j<=i;j++)
{
if(f[j]<f[j+1])
{
temp=f[j];
f[j]=f[j+1];
f[j+1]=temp;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
flag=1;
}
}
i--;
}
}
int main()

{
int N; //1~100
cin>>N;
Creat(N);
DFS(N);
mysort(N);
for(int i=1;i<=N;i++)
{
if(i!=N)
{
cout<<a[i]<<" ";
}
else
{
cout<<a[i]<<endl;
}
}
return 0;
}

