/*
拓扑排序用于解决有向图中的顶点先后顺序问题
算法思想:依次输出入度为0的顶点,并删除其有向边
*/
#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
#include<functional>
using namespace std;
const int MAXN=500;
int inDegree[MAXN];
vector<int> graph[MAXN];
vector<int> TopuSort(int n)
{
priority_queue<int, vector<int>, greater<int> > que;
vector<int> v;
for(int i=1;i<=n;i++)
{
if(inDegree[i]==0)
{
que.push(i);
}
}
while(!que.empty())
{
int u =que.top();
que.pop();
v.push_back(u);
vector<int> vec = graph[u];
for(int j=0;j<vec.size();j++)
{
int number =vec[j];
inDegree[number]--;
if(inDegree[number]==0)
{
que.push(number);
}
}
}
return v;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
memset(inDegree,0,sizeof(inDegree));
memset(graph,0,sizeof(graph));
int from,to;
for(int i=0;i<m;i++)
{
cin>>from>>to;
graph[from].push_back(to);
inDegree[to]++;
}
vector<int> v = TopuSort(n);
for(int i=0;i<n;i++)
{
if(i==0)
{
cout<<v[0];
}
else{
cout<<" "<<v[i];
}
}
cout<<endl;
}
return 0;
}
图论04—拓扑排序
最新推荐文章于 2024-08-10 10:46:16 发布