拓扑排序
作者:
橙外
,
2021-02-03 22:52:53
,
所有人可见
,
阅读 424
拓扑排序 : 记录入度,入度为0就入队
#include <cstdio>
#include <vector>
#include <iostream>
#include <queue>
using namespace std;
const int N=101;
int n,m,in[N],x,y,ans[N],sum,top;
vector < int > f[N];
queue < int > q;
void inp()
{
scanf ("%d %d",&n,&m);
while( cin >> x >> y)
{
if( x == 0 && y == 0) break;
f[x].push_back(y);
in[y]++; //入度加一;
}
}
void work()
{
for (int i = 1; i <= n; i++)
if( in[i] == 0) q.push(i);
while(!q.empty())
{
sum = q.front();
q.pop();
ans[++top] = sum;
for (int i = 0; i < f[sum].size(); i++)
{
in[f[sum][i]]--;
if(in[f[sum][i]] == 0) q.push(f[sum][i]);
}
}
}
void putp()
{
for (int i = 1; i <= n ; i++)
printf("%d ",ans[i]);
}
int main()
{
inp();
work();
putp();
return 0;
}
了解了解