拓扑排序--九度.1449.[优先级队列实现小顶堆]
2017-02-28 20:47
246 查看
题目:http://ac.jobdu.com/problem.php?pid=1449
思路: 题目要求输出排名实际就是输出拓扑序列,使用vector和queue并不难实现;
主要是其要求在有多个序列满足时,仅输出号码排列最小的那个;想到的解决办法是用
priority_queue实现小顶堆
保存入度为0的结点,这样每次出队列的都是其中号码最小的,当有多个拓扑序列时,自然满足。
思路: 题目要求输出排名实际就是输出拓扑序列,使用vector和queue并不难实现;
主要是其要求在有多个序列满足时,仅输出号码排列最小的那个;想到的解决办法是用
priority_queue实现小顶堆
保存入度为0的结点,这样每次出队列的都是其中号码最小的,当有多个拓扑序列时,自然满足。
#include<cstdio> #include<vector> #include<queue> #include<functional> using namespace std; vector<int> list[510]; //优先级队列实现小顶堆 priority_queue<int, vector<int>, greater<int> > Q; int inCount[510]; //优先级队列实现小顶堆,这样每次选择入度为0的结点中号码最小的, //保证了当有多了排列时,输出的是号码最小的 int main() { int n, m; while (scanf("%d%d", &n, &m) != EOF) { int a, b; //清空数据 while (Q.empty() == false) Q.pop(); for (int i = 1; i <= n; i++) { list[i].clear(); inCount[i] = 0; } //输入数据 for (int i = 0; i < m; i++) { scanf("%d%d", &a, &b); list[a].push_back(b); inCount[b]++; } for (int i = 1; i <= n; i++)//入度为0的结点入队列 if (0 == inCount[i]) Q.push(i); int cnt = 0;//记录入度变为0的点数 while (Q.empty() == false) { int nowp = Q.top(); Q.pop(); if (++cnt != n)//输出 printf("%d ", nowp); else printf("%d\n", nowp); for (int i = 0; i < list[nowp].size(); i++) { int temp = list[nowp][i];//遍历节点nowp的邻接表 inCount[temp]--;//入度减1 if (0 == inCount[temp]) //若入度变为0,则入队列 Q.push(temp); } }//while-queue }//while-input return 0; }
相关文章推荐
- 基于最小二叉堆的优先级队列-C#实现,以此为基础的K路合并排序算法
- 关于优先级队列的实现
- 优先级队列实现哈夫曼树的编码和译码
- 优先级队列实现哈夫曼树的编码和译码
- 堆和堆排序(堆实现优先级队列)
- 用链表实现优先级队列
- 循环队列与优先级队列的Java实现
- 第六章堆排序之“优先级队列实现先进先出队列和栈”(练习6.5-6)
- 算法导论Java实现-优先级队列(6.5章节)
- java实现 数据结构:链表、 栈、 队列、优先级队列、哈希表
- 顺序表实现优先级队列
- 优先级队列——用C++模板实现
- C语言实现的优先级队列
- 基于大顶堆实现的最大优先级队列
- 泛型优先级队列的实现
- 算法-----堆结构实现优先级队列
- W. :利用最小优先级队列实现对k个已序队列的合并排序。习题6.5-8
- 优先级队列的Java ,C++ STL,堆实现
- 优先级队列(可用堆实现)
- 读《算法导论》我来C语言实现(3)——堆排序和优先级队列