码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1285 确定比赛名次

时间:2015-08-11 13:39:24      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

简单的拓扑排序,按字典序输出。

 

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,u,v;
const int maxn=1111;//设置节点数量
int InDegree[maxn];//入度
int pri[maxn];//输出
int tot;//输出
int Start,End;//顶点编号的开始和结束
vector<int>G[maxn];
struct cmp1
{
    bool operator ()(int &a,int &b)
    {
        return a>b;//最小值优先
    }
};
priority_queue<int,vector<int>,cmp1>Q;
void TopoSort()
{
    int i;
    for(i=Start; i<=End; i++)
        if(!InDegree[i])
            Q.push(i);
    while(!Q.empty())
    {
        int h=Q.top(); Q.pop();
        pri[tot]=h; tot++;
        for(i=0; i<G[h].size(); i++)
        {
            InDegree[G[h][i]]--;
            if(!InDegree[G[h][i]])
                Q.push(G[h][i]);
        }
    }
    if(tot==n)
    {
        for(int i=0; i<tot; i++)
        {
            if(i<tot-1) printf("%d ",pri[i]);
            else printf("%d\n",pri[i]);
        }
    }
}

void init()
{
    tot=0;
    for(int i=0; i<=n; i++) G[i].clear();
    while(!Q.empty()) Q.pop();
    memset(InDegree,0,sizeof(InDegree));
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
// 初始化,顶点编号从 1 开始,顶点编号以 n 结束
        init();
        Start=1;
        End=n;
//构造有向图
        for(int i=0; i<m; i++)
        {
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
            InDegree[v]++;
        }
        TopoSort();
    }
    return 0;
}

 

HDU 1285 确定比赛名次

标签:

原文地址:http://www.cnblogs.com/14jsj221/p/4720515.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!