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

来源:互联网 发布:中信证券软件下载 编辑:程序博客网 时间:2024/06/06 09:39
  • 以下内容概括自:
    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
原创粉丝点击