您的位置:首页 > 其它

拓扑排序--九度.1449.[优先级队列实现小顶堆]

2017-02-28 20:47 246 查看
题目:http://ac.jobdu.com/problem.php?pid=1449

思路: 题目要求输出排名实际就是输出拓扑序列,使用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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: