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

题目: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值