poj 2367 Genealogical tree

裸的拓扑排序 图用邻接表表示

方法是dfs

#include<stdio.h>
#include
<string.h>
const int MAXN = 1000;
struct edge{
int u, v, next;
}e[MAXN];
int n;
int first[MAXN], cnt;
bool visit[MAXN], f;
int sort[MAXN], top;
void dfs(int s){
if(visit[s])
return;
visit[s]
= true;
for(int x = first[s]; x != -1; x = e[x].next){
if(!visit[e[x].v])
dfs(e[x].v);
}
sort[
++top] = s;
}
void toposort(){
memset(visit,
false, sizeof(visit));
top
= -1;
for(int i = 1; i <= n; ++i){
if(!visit[i])
dfs(i);
}
}
int main(){
scanf(
"%d",&n);
memset(first,
-1, sizeof(first));
for(int i = 1, cnt = 0; i <= n; ++i){
int a;
while(true){
scanf(
"%d",&a);
if(!a)
break;
e[cnt].u
= i;
e[cnt].v
= a;
e[cnt].next
= first[i];
first[i]
= cnt;
cnt
++;
}
}
toposort();
bool f = true;
while(top != -1){
if(f)
f
= false;
else
printf(
" ");
printf(
"%d",sort[top--]);
}
printf(
"\n");
return 0;
}

posted @ 2011-04-30 06:34  L..  阅读(240)  评论(0编辑  收藏  举报