zoukankan      html  css  js  c++  java
  • hdu 1285 拓扑排序+优先队列

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1285

    题目大意:

      给定一个有向无环图,要求得到该图的拓扑序列(我是看过拓扑排序的资料后才知道),如果有多个序列,点标号小的点在前面;

    题目分析:

      直接拓扑排序即可,但是由于要考虑点标号小的在前面所以使用优先队列来写;

    代码:

    hdu1285
     1 /*2012-04-25 18:07:36    Accepted    1285    15MS    332K    1316 B    C++*/
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <cmath>
     5 #include <iostream>
     6 #include <algorithm>
     7 #include <vector>
     8 #include <queue>
     9 using namespace std;
    10 
    11 #define mpair make_pair
    12 #define pii pair<int,int>
    13 #define MM(a,b) memset(a,b,sizeof(a));
    14 typedef long long lld;
    15 typedef unsigned long long u64;
    16 template<class T> bool up_max(T& a,const T& b){return b>a? a=b,1 : 0;}
    17 template<class T> bool up_min(T& a,const T& b){return b<a? a=b,1 : 0;}
    18 #define maxn 510
    19 
    20 int n,m;
    21 vector<int> adj[maxn];
    22 
    23 int in[maxn];
    24 priority_queue< int, vector<int>, greater<int> > Q;
    25 void Topsort(){
    26     while( !Q.empty() ) Q.pop();
    27     for(int i=1;i<=n;++i) if( !in[i] ) Q.push(i);
    28     while( !Q.empty() ){
    29         int u= Q.top();
    30         printf("%d", u);
    31         Q.pop();
    32         for(int i=0;i<adj[u].size();++i){
    33             int v= adj[u][i];
    34             if( --in[v] == 0 )
    35                 Q.push( v );
    36         }
    37         if( Q.empty() ) puts("");
    38         else printf(" ");
    39     }
    40 }
    41 
    42 int main()
    43 {
    44     while( cin>>n>>m ){
    45         for(int i=1;i<=n;++i) adj[i].clear(), in[i]= 0;
    46         for(int i=1;i<=m;++i){
    47             int u,v;
    48             scanf("%d%d", &u, &v );
    49             in[v]++;
    50             adj[u].push_back( v );
    51         }
    52         Topsort();
    53     }
    54 }
  • 相关阅读:
    Linux C/C++编程之(十四)文件操作相关函数
    javascript语法之循环语句
    javascript语法之流程控制语句
    javascript语法之字符串转换成数字
    javascript语法之声明变量
    认识javascript
    css之定位
    css之盒子模型案例
    常见Css样式
    Css详解之(伪类选择器)
  • 原文地址:https://www.cnblogs.com/yimao/p/2470268.html
Copyright © 2011-2022 走看看