【u243】拓扑排序

Time Limit: 1 second
Memory Limit: 128 MB

【问题描述】

一些历史迷们打算把历史上的一些大事件按时间顺序列出来。但是,由于资料不全,每个事件发生的具体时间都没有找到。幸运的
是,他们记得一些事件之间的先后关系。他们把事件分别编号1,2,3,……n,然后把一些先后关系列出。不过,这些复杂的先
后关系仍然把他们难倒了。你能够帮助他们吗?

【输入格式】

输入文件event.in。第一行是两个整数n,m(1<=n<=1000,1<=m<=100000),分别表示事件数和已知的先后关系数。接下来m行,第i
行是两个整数xi,yi(1<=xi,yi<=n),表示事件xi比事件yi先发生。

【输出格式】

输出文件event.out。按事件发生的时间顺序列出事件的编号,每行一个,若存在多种可能,输出第一个事件编号最小的,若第一
个事件编号相同,则输出第二个事件编号最小的……;若没有满足条件的编号序列,输出一行’Error!’)。

【数据规模】

Sample Input1

3 2
1 2
1 3

Sample Output1

1
2
3

【题目链接】:http://noi.qz5z.com/viewtask.asp?id=u243

【题解】

就是裸的拓扑排序;
那些编号最小什么的限制;只要你是从1到n循环就能保证;
然后遇到在循环的过程中没有入度为0的点则输出无解信息;
虽然很简单,但是蒟蒻还是倍感压力,因为不是熟悉的算法。嘛不算熟悉(练)

【完整代码】

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <vector>
#include <stack>
#include <string>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second

typedef pair<int,int> pii;
typedef pair<LL,LL> pll;

void rel(LL &r)
{
    r = 0;
    char t = getchar();
    while (!isdigit(t) && t!='-') t = getchar();
    LL sign = 1;
    if (t == '-')sign = -1;
    while (!isdigit(t)) t = getchar();
    while (isdigit(t)) r = r * 10 + t - '0', t = getchar();
    r = r*sign;
}

void rei(int &r)
{
    r = 0;
    char t = getchar();
    while (!isdigit(t)&&t!='-') t = getchar();
    int sign = 1;
    if (t == '-')sign = -1;
    while (!isdigit(t)) t = getchar();
    while (isdigit(t)) r = r * 10 + t - '0', t = getchar();
    r = r*sign;
}

const int MAXN = 1100;
const int dx[5] = {0,1,-1,0,0};
const int dy[5] = {0,0,0,-1,1};
const double pi = acos(-1.0);

int n,m;
int du[MAXN];
vector <int> ans,a[MAXN];

int main()
{
    //freopen("F:\\rush.txt","r",stdin);
    rei(n);rei(m);
    rep1(i,1,m)
    {
        int x,y;
        rei(x);rei(y);
        du[y]++;
        a[x].pb(y);
    }
    rep1(i,1,n)
    {
        int k = -1;
        rep1(j,1,n)
            if (du[j]==0)
            {
                k = j;
                break;
            }
        if (k==-1)
        {
            puts("Error!");
            return 0;
        }
        ans.pb(k);
        du[k] = -1;
        int len = a[k].size();
        rep1(j,0,len-1)
        {
            int y = a[k][j];
            du[y]--;
        }
    }
    rep1(i,0,n-1)
        cout << ans[i]<<endl;
    return 0;
}
posted @ 2017-10-04 18:45  AWCXV  阅读(150)  评论(0编辑  收藏  举报