SSL2844 2017年11月8日提高组T2 奇怪的队列(线段树贪心)

来源:互联网 发布:淘宝店铺综合排名查询 编辑:程序博客网 时间:2024/06/01 09:19

2017年11月8日提高组T2 奇怪的队列

Description

nodgd的粉丝太多了,每天都会有很多人排队要签名。
今天有n个人排队,每个人的身高都是一个整数,且互不相同。很不巧,nodgd今天去忙别的事情去了,就只好让这些粉丝们明天再来。同时nodgd提出了一个要求,每个人都要记住自己前面与多少个比自己高的人,以便于明天恢复到今天的顺序。
但是,粉丝们或多或少都是有些失望的,失望使她们晕头转向、神魂颠倒,已经分不清楚哪一边是“前面”了,于是她们可能是记住了前面比自己高的人的个数,也可能是记住了后面比自己高的人的个数,而且他们不知道自己记住的是哪一个方向。
nodgd觉得,即使这样明天也能恢复出一个排队顺序,使得任意一个人的两个方向中至少有一个方向上的比他高的人数和他记住的数字相同。可惜n比较大,显然需要写个程序来解决,nodgd很忙,写程序这种事情就交给你了。

Input

第一行输入一个整数n,表示指令的条数。
接下来��行,每行两个整数ai,bi,表示一个人的身高和她记住的数字,保证身高互不相同。

Output

输出一行,这个队列里从前到后的每个人的身高。如果有多个答案满足题意,输出字典序最小。如果不存在满足题意的排列,输出“impossible”(不含引号)。

Sample Input

输入1:
4
4 1
3 1
6 0
2 0
输入2:
6
1 5
8 0
3 1
4 0
2 0
6 0
Sample Output

输出1:
2 4 3 6
输出2:
1 2 4 3 6 8
Hint

【数据规模和约定】
对于40%的数据,n<=10;
对于60%的数据,n<=1000;
对于100%的数据,n<=100000。

分析:要求字典序最小那显然先排序,然后对每个身高我们知道前面或后面有多少比他高,那只要在前面或后面留出这么多空位,放在一个靠前的位置就好了,线段树维护区间空位个数。

代码

#include <cstdio>#include <algorithm>#define N 100005using namespace std;struct arr{    int x,y;}a[N];struct tnode{    int l,r,n;}tr[N*5];int n,b[N];int so(arr p,arr q){    return p.x<q.x;}int min(int x,int y){    return x<y?x:y;}void build(int p){    if (tr[p].l==tr[p].r)    {        tr[p].n=1;        return;    }    int mid=(tr[p].l+tr[p].r)/2;    tr[p*2].l=tr[p].l;    tr[p*2].r=mid;    tr[p*2+1].l=mid+1;    tr[p*2+1].r=tr[p].r;    build(p*2);    build(p*2+1);    tr[p].n=tr[p*2].n+tr[p*2+1].n;}void insert(int p,int k,int x){    tr[p].n--;    if (tr[p].l==tr[p].r)    {        b[tr[p].l]=x;        return;    }    int mid=(tr[p].l+tr[p].r)/2;    if (k<=tr[p*2].n) insert(p*2,k,x);        else insert(p*2+1,k-tr[p*2].n,x);}int main(){    freopen("queue.in","r",stdin);    freopen("queue.out","w",stdout);    scanf("%d",&n);    for (int i=1;i<=n;i++)        scanf("%d%d",&a[i].x,&a[i].y);    sort(a+1,a+n+1,so);    tr[1].l=1;    tr[1].r=n;    build(1);    bool fl=false;    for (int i=1;i<=n;i++)        if (a[i].y>n-i)        {            fl=true;            break;        }        else insert(1,min(a[i].y+1,n-i-a[i].y+1),a[i].x);    if (fl) printf("impossible");        else for (int i=1;i<=n;i++) printf("%d ",b[i]);}
原创粉丝点击