JZOJ5443. 【NOIP2017提高A组冲刺11.2】字典序

来源:互联网 发布:大学生适合开淘宝店吗 编辑:程序博客网 时间:2024/06/05 10:18

Description

你需要构造一个1~n的排列,使得它满足m个条件,每个条件形如(ai,bi),表示ai必须在bi前面。在此基础上,你需要使它的字典序最小。

Input

第一行两个正整数n,m。接下来m行每行两个数ai,bi。

Output

输出一行n个整数表示答案。如果不存在这样的排列,输出-1。

Sample Input

5 4
5 4
5 3
4 2
3 2

Sample Output

1 5 3 4 2

Data Constraint

对于20%的数据,n,m<=10。
对于40%的数据,n,m<=200。
对于60%的数据,n,m<=1000。
对于100%的数据,n,m<=100000。

题解

这题是在简单,
如果不考虑字典序,就随便搞一个拓扑序就好了。

如果要字典序最小,
那么每次选就选能选中最小的那个。
用优先队列维护。

code

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <queue>#define N 100003using namespace std;char ch;void read(int& n){    n=0;    ch=getchar();    while(ch<'0'||ch>'9')ch=getchar();    while('0'<=ch && ch<='9')n=(n<<1)+(n<<3)+ch-'0',ch=getchar();}void write(int x){    if(x>9)write(x/10);    putchar(x%10+48);}int f[N],ans[N],n,m,x,y;int nxt[N],b[N],to[N],tot;struct node{    int x;}t;priority_queue <node> q;bool operator <(node a,node b){    return a.x>b.x;}void ins(int x,int y){    nxt[++tot]=b[x];    to[tot]=y;    b[x]=tot;    f[y]++;}int main(){    freopen("dictionary.in","r",stdin);    freopen("dictionary.out","w",stdout);    read(n);read(m);    for(int i=0;i<m;i++)        read(x),read(y),ins(x,y);    for(int i=1;i<=n;i++)        if(f[i]==0)t.x=i,q.push(t);    tot=0;    while(!q.empty())    {        t=q.top();        ans[++tot]=t.x;        q.pop();        for(int i=b[t.x];i;i=nxt[i])        {            f[to[i]]--;            if(f[to[i]]==0)t.x=to[i],q.push(t);        }    }    if(tot<n)    {        putchar('-');        putchar('1');        return 0;    }    for(int i=1;i<=n;i++)        write(ans[i]),putchar(' ');    return 0;}
阅读全文
0 0
原创粉丝点击