拓扑排序
本题要点:
1、如果要按字典序输出各个队的编号,用 优先队列 priority_queue来存放节点编号,
注意 priority_queue 默认是大根堆,要写成小根堆 priority_queue<int, vector, greater >
2、 n <= 500, 有可能出现重边的情况,用 邻接矩阵 mp[MaxN][MaxN] 来去重。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <functional>
#include <vector>
#include <queue>
using namespace std;
const int MaxN = 510, MaxM = 250010;
bool mp[MaxN][MaxN];
int head[MaxN], deg[MaxN], ver[MaxM], Next[MaxM], a[MaxN];
int n, m, tot, cnt;void add(int x, int y)
{
ver[++tot] = y, Next[tot] = head[x], head[x] = tot;deg[y]++;
}void topsort()
{
cnt = 0;priority_queue<int, vector<int>, greater<int> > pq;for(int i = 1; i <= n; ++i){
if(deg[i] == 0){
pq.push(i); }}while(pq.size()){
int x = pq.top(); pq.pop();a[++cnt] = x;for(int i = head[x]; i; i = Next[i]){
int y = ver[i];if(--deg[y] == 0){
pq.push(y);}}}
}int main()
{
int x, y;while(scanf("%d%d", &n, &m) != EOF){
tot = 0;memset(head, 0, sizeof head);memset(Next, 0, sizeof Next);memset(deg, 0, sizeof deg);memset(mp, false, sizeof mp);for(int i = 0; i < m; ++i){
scanf("%d%d", &x, &y);if(!mp[x][y]){
mp[x][y] = true;add(x, y);}}topsort();printf("%d", a[1]);for(int i = 2; i <= n; ++i){
printf(" %d", a[i]);}printf("\n");}return 0;
}/* 4 3 1 2 2 3 4 3 *//* 1 2 4 3 */