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

##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 100003
using 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值