链接:http://acm.hdu.edu.cn/showproblem.php?pid=1285
4 3 1 2 2 3 4 3
1 2 4 3
简单的拓扑排序,唯一可能出现的地方就是题目中要求同样拓扑序的两个编号小的要在前面,这点可以通过优先队列或者堆来实现;
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <queue> #define MAXN 505 #define RST(N)memset(N, 0, sizeof(N)) using namespace std; int n, m, u, v; bool first; int graph[MAXN][MAXN], degree[MAXN]; //图的邻接矩阵,每个顶点的入度; priority_queue <int, vector<int>, greater<int> > q; //优先队列; void Init() { RST(graph), RST(degree); //初始化数组; while(!q.empty()) q.pop(); //队列清空; for(int i=0; i<m; i++) { scanf("%d %d", &u, &v); if(!graph[u][v]) { //防止重边; graph[u][v] = 1; degree[v]++; } } first = 1; for(int i=1; i<=n; i++) if(!degree[i]) q.push(i); } int main() { while(~scanf("%d %d", &n, &m)) { Init(); while(!q.empty()) { int current = q.top(); q.pop(); if(first) { printf("%d", current); first = 0; } else printf(" %d", current); for(int i=1; i<=n; i++) if(graph[current][i]) { degree[i]--; if(degree[i] == 0) q.push(i); } } puts(""); } return 0; }
HDU 1285 确定比赛名次(拓扑排序+优先队列),布布扣,bubuko.com
原文地址:http://blog.csdn.net/keshacookie/article/details/24991067