拓扑排序
代码如下:
#include <stdio.h>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
#define N 501
vector<int> edge[N];
int inDegree[N]; // 保存各点入度
queue<int> out; // 用于输出
queue<int> q;
int tmp[N];
int main()
{
int n, m;
while (scanf("%d%d", &n, &m) != EOF && n != 0)
{
for (int i = 1; i <= n; i++)
{
edge[i].clear();
inDegree[i] = 0;
}
while (!q.empty()) q.pop();
while (!out.empty()) out.pop();
while (m--)
{
int a, b;
scanf("%d%d", &a, &b);
inDegree[b]++;
edge[a].push_back(b);
}
for (int i = 1; i <= n; i++)
if (0 == inDegree[i]) q.push(i); // 入度为0的压入队列
while (!q.empty())
{
int size = q.size();
int k = 0;
while (!q.empty())
{
tmp[k++] = q.front();
q.pop();
}
sort(tmp, tmp + size); // 将队列中的元素弹出,排好序再压入
for (int i = 0; i < size; i++)
q.push(tmp[i]);
int newp = q.front();
out.push(newp);
q.pop();
for (int i = 0; i < edge[newp].size(); i++) // 修改各点入度
if (0 == --inDegree[edge[newp][i]]) q.push(edge[newp][i]); // 入度为0的压入队列
}
for (int i = 0; i < n; i++)
{
if (i != n - 1) printf("%d ", out.front());
else printf("%d", out.front());
out.pop();
}
printf("\n");
}
return 0;
}