讲解
引入
先找到没有父亲的人,把他们标为第1代,他们的孩子,如果没有别的长辈,那就是第2代,如果有那就是那个长辈+1代。最后按代的顺序输出。
实现:
1 建成一个图,把“a是b长辈”变为“a到b有一条有向边”,并且b的入度 。
2 找到入度为0的点,放入一个结构中
3 结构中的点开始搜索,把他的孩子入度 ,如果入度到0就把他放到结构中
4 重复3,知道没有点在结构中
如果要求遍历时字典序最小,这个结构可以是堆,如果要求按“代”(前文)的顺序输出,可以用队列,按情况还可以用栈等数据结构。
拓扑排序就是这么简单。
代码
#include<cstdio>
#include<vector>
using namespace std;
int swap_f,heap_f;
void swap(int&a,int&b){
swap_f=a,a=b,b=swap_f;
}
class heap{
int n,*a;
public:
heap();
heap(int x){
a=new int[x];
}
void push(int x){
a[n]=x;
heap_f=n++;
while(heap_f&&a[heap_f]<a[heap_f>>1]) swap(a[heap_f],a[heap_f>>1]),heap_f>>=1;
}
void pop(){
a[0]=a[--n];
heap_f=1;
while(heap_f<n){
if (heap_f<n-1&&a[heap_f+1]<a[heap_f]) ++heap_f;
if(a[heap_f]>=a[heap_f>>1]) return;
swap(a[heap_f],a[heap_f>>1]);
heap_f<<=1;
}
}
int top(){
return a[0];
}
bool empty(){
return(n==0);
}
}h(101); //只是实现了一个堆而已,这里其实用队列就好
int n,r[101],x;
vector<int>G[101]; //vector邻接表
int main(){
scanf("%d",&n);
for(int c=1,a;c<=n;++c){
scanf("%d",&a);
while(a){
++r[a];
G[c].push_back(a);
scanf("%d",&a);
} //输入建图
}
for(int c=1;c<=n;++c) if(r[c]==0) h.push(c); //找到入度为0
while(!h.empty()){
printf("%d ",x=h.top());
h.pop();
for(int c:G[x]){
--r[c];
if(r[c]==0) h.push(c);
}//遍历
}
return 0;
}不难看出,每条边走了一次,加上一开始查找入度为0,一共是 的
如果判断是否有拓扑排序可以直接看遍历完是不是所有点都进过一次结构