杭电1285——确定比赛名次

来源:互联网 发布:高达00q全刃式淘宝 编辑:程序博客网 时间:2024/05/06 00:43

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

这是写的第一个拓扑排序题目,算是水题吧,能过就好。

但还是错了几次:刚开始不知道如何处理输出的顺序问题,原来改用优先队列(priority_queue)就行了,也是百度才知道输入可能存在重复的边。

 

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

struct node{
    int n;
    bool operator <(const node &a) const{
        return a.n<n;
    }
}o;
using namespace std;
int N,M,map[550][550],du[550];

void top_order(){
    priority_queue<node> q;
    for(int i=1;i<=N;i++)
        if(!du[i]) {
            o.n=i;
            q.push(o);
        }
    while(!q.empty())
    {
        int tmp=q.top().n;
        q.pop();
        cout<<tmp;
        for(int i=1;i<=N;i++)
            if(map[tmp][i])
            {
                du[i]--;
                if(!du[i]){
                    o.n=i;
                    q.push(o);
                }
            }
        if(!q.empty()) cout<<" ";
        else cout<<endl;
    }
}

int main(){
    while(cin>>N)
    {
        cin>>M;
        if(!N && !M) break;
        memset(map,0,sizeof(map));
        memset(du,0,sizeof(du));
        for(int i=0;i<M;i++)
        {
            int tx,ty;
            cin>>tx>>ty;
            if(!map[tx][ty]){
                map[tx][ty]=1;
                du[ty]++;
            }
        }
        top_order();
    }
    return 0;
}

 

0 0