#include <iostream>
using namespace std;
const int N = 100010;
int n,m;
int Value[N];//存储节点
int Next[N];//记录下一个节点的下标
int Head[N];//记录头结点
int Index;//存储位置
int Degree[N];//记录每个节点的入度
int Queue[N];//手工模拟的队列
void Add(int Start, int End)
{
Value[Index] = End;
Next[Index] = Head[Start];
Head[Start] = Index;
Index++;
}
bool ToopSort()
{
//队列的头尾
int Start = 0;
int End = -1;
for(int i = 1; i <= n; i++)
{
if(!Degree[i])
{
Queue[++End] = i;
}
}
while(Start <= End)
{
int NodeHead = Queue[Start++];
for(int i = Head[NodeHead]; i != -1; i = Next[i])
{
int j = Value[i];
Degree[j]--;
if(0 == Degree[j])
{
Queue[++End] = j;
}
}
}
return End == (n-1);
}
int main(int argc, char** argv)
{
//初始化头结点都为-1 代表没有后继元素
fill(Head,Head+N,-1);
cin>>n>>m;
for(int i = 0; i < m; i++)
{
int Start,End;
scanf("%d%d",&Start,&End);
Add(Start,End);
//入度+1
Degree[End]++;
}
if(ToopSort())
{
for(int i = 0; i < n; i++)
{
printf("%d ",Queue[i]);
}
}
else
{
cout<<"-1"<<endl;
}
return 0;
}
Toop排序
最新推荐文章于 2022-11-10 11:16:53 发布