码迷,mamicode.com
首页 > 编程语言 > 详细

HDU-1285-确定比赛名次-拓扑排序(模板)

时间:2015-07-30 21:31:17      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:hdu1285   确定比赛名次   拓扑排序   图论   模板   

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

这是一道拓扑排序的模板题,用来学拓扑排序很好。我的算法62ms过的,效率还是很低,不过很好理解;用一个结构体记录每个点的入度出度就搞定了;

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
#include<cmath>
#include<stack>
#include<set>
#include<vector>
#include<algorithm>
#define LL long long
#define inf 1<<30
using namespace std;
const int N=505;
int a,b,n,m,top;
struct node
{
    int in;     //  记录入度;
    int out;    //  记录出度;
}s[N];
bool Map[N][N]; //  用来标记a到b
bool vis[N];    //  用来标记是否已经Push输出了;
int st[N];
void Push(int i)    //  存储最后排序结构;
{
    st[++top]=i;
}
void TopSort()
{
    int flag=1;
    while(flag){
        flag=0;     //  用于判断是否全部Push;
        for(int i=1;i<=n;i++){          //  遍历每一个点,
            if(!vis[i]&&s[i].in==0){    //  从小到大找出入度为零的点,然后Push;
                flag=1;
                Push(i);
                vis[i]=true;
                for(int j=1;j<=n;j++){      //  因为i已经输出,所以所有有i到j入度的j的入度都要减一;
                    if(Map[i][j]) --s[j].in;
                }
                break;      //  加一个这个才能够保证是按照从小到大输出;orz....
            }
        }
    }
}
void Print()        //  打印结果;
{
    for(int i=1;i<top;i++) printf("%d ",st[i]);
    printf("%d\n",st[top]);
}
int main()
{
    while(~scanf("%d%d",&n,&m)){
        memset(Map,false,sizeof(Map));
        memset(vis,false,sizeof(vis));
        memset(s,0,sizeof(s));
        for(int i=1;i<=m;i++){
            scanf("%d%d",&a,&b);
            if(!Map[a][b]){     //  数据可能有重复的边,一不小心就WA了;
                s[a].out++;
                s[b].in++;
            }
            Map[a][b]=true;
        }
        top=0;
        TopSort();
        Print();
    }
    return 0;
}


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU-1285-确定比赛名次-拓扑排序(模板)

标签:hdu1285   确定比赛名次   拓扑排序   图论   模板   

原文地址:http://blog.csdn.net/wlxsq/article/details/47155465

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