拓扑排序(Topological Order 基础篇)—— 确定比赛名次 (HDU 1285 )

  • 以下内容概括自:
    http://www.cnblogs.com/skywang12345/p/3711489.html#anchor1

  • 概念:
    将一个有向无环图(Directed Acyclic Graph DAG)进行排序进而得到一个有序的线性序列。

  • 基本步骤:

    1. 构造一个队列Q 和 拓扑排序的结果队列T;
    2. 把入度为0的节点加入Q;
    3. 当Q不为空的时候,执行下列步骤:
      1. 从Q中取出一个顶点n,并放入T;
      2. 对n的每一个邻接点m去掉边 < n,m >;
      3. 如果m入度为0,则把m放入Q;
  • 练习:

    http://acm.hdu.edu.cn/showproblem.php?pid=1285

  • 分析&题解:
    非常裸的拓扑排序,不过要小心一点,就是它的输入数据会给出重复的边,所以记录入度的时候需要小心。

  • AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

int Map[666][666];
int Degree[666];
int Ans[666];
int N, M;

priority_queue <int , vector<int>,  greater<int> >Q;

int main()
{
    while(cin >> N >> M)
    {
        memset(Map, 0, sizeof(Map));
        memset(Degree, 0, sizeof(Degree));
        for(int i=0;i<M;i++)
        {
            int x,y;
            cin >> x >> y;
            if(Map[x][y] != 1)
            {
                Map[x][y] = 1;
                Degree[y]++;
            }
        }
        while(!Q.empty()) Q.pop();
        for(int i=1;i<=N;i++)
        {
            if(Degree[i] == 0)
            {
                Q.push(i);
            }
        }

        int loc = 0;
        while(!Q.empty())
        {
            int tmp = Q.top();
            //cout << tmp << endl;
            Ans[loc++] = tmp;
            Q.pop();
            for(int i=1;i<=N;i++)
            {
                if(Map[tmp][i] == 1)
                {
                    Map[tmp][i] = 0;
                    Degree[i]--;
                    if(Degree[i] == 0)
                        Q.push(i);
                }
            }
        }

        for(int i=0;i<N-1;i++)
            cout << Ans[i]  << " ";
        cout << Ans[N-1] << endl;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值