以下内容概括自:
http://www.cnblogs.com/skywang12345/p/3711489.html#anchor1概念:
将一个有向无环图(Directed Acyclic Graph DAG)进行排序进而得到一个有序的线性序列。基本步骤:
- 构造一个队列Q 和 拓扑排序的结果队列T;
- 把入度为0的节点加入Q;
- 当Q不为空的时候,执行下列步骤:
- 从Q中取出一个顶点n,并放入T;
- 对n的每一个邻接点m去掉边 < n,m >;
- 如果m入度为0,则把m放入Q;
练习:
分析&题解:
非常裸的拓扑排序,不过要小心一点,就是它的输入数据会给出重复的边,所以记录入度的时候需要小心。AC代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int Map[666][666];
int Degree[666];
int Ans[666];
int N, M;
priority_queue <int , vector<int>, greater<int> >Q;
int main()
{
while(cin >> N >> M)
{
memset(Map, 0, sizeof(Map));
memset(Degree, 0, sizeof(Degree));
for(int i=0;i<M;i++)
{
int x,y;
cin >> x >> y;
if(Map[x][y] != 1)
{
Map[x][y] = 1;
Degree[y]++;
}
}
while(!Q.empty()) Q.pop();
for(int i=1;i<=N;i++)
{
if(Degree[i] == 0)
{
Q.push(i);
}
}
int loc = 0;
while(!Q.empty())
{
int tmp = Q.top();
//cout << tmp << endl;
Ans[loc++] = tmp;
Q.pop();
for(int i=1;i<=N;i++)
{
if(Map[tmp][i] == 1)
{
Map[tmp][i] = 0;
Degree[i]--;
if(Degree[i] == 0)
Q.push(i);
}
}
}
for(int i=0;i<N-1;i++)
cout << Ans[i] << " ";
cout << Ans[N-1] << endl;
}
}