http://acm.hdu.edu.cn/showproblem.php?pid=5493
Problem Description N people numbered from 1 to N are waiting in a bank for service. They all stand in a queue, but the queue never moves. It is lunch time now, so they decide to go out and have lunch first. When they get back, they don’t remember the exact order of the queue. Fortunately, there are some clues that may help.
Input The first line of input contains a number T indicating the number of test cases (T≤1000 ).
Output For each test case, output a single line consisting of “Case #X: S”. X is the test case number starting from 1. S is people’s heights in the restored queue, separated by spaces. The solution may not be unique, so you only need to output the smallest one in lexicographical order. If it is impossible to restore the queue, you should output “impossible” instead.
Sample Input
3 3 10 1 20 1 30 0 3 10 0 20 1 30 0 3 10 0 20 0 30 1
Sample Output
Case #1: 20 10 30 Case #2: 10 20 30 Case #3: impossible
|
说的是一个队列,给定人的身高和他以为的他前面或者后面比他高的人,求身高序最小的排列
用树状数组计数,0代表有人,1代表空。
先按照身高排序,矮的在前 p代表前面有多少个位置,位置数要最小。
二分出位置pos,在pos处占据这个人
#include<stdio.h>
#include<string>
#include<string.h>
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
typedef long long ll;
const int MAXN=200000+5;//最大元素个数
int n;//元素个数
int c[MAXN],ans[MAXN];//c[i]==A[i]+A[i-1]+...+A[i-lowbit(i)+1]
//返回i的二进制最右边1的值
int lowbit(int i)
{
return i&(-i);
}
//返回A[1]+...A[i]的和
int sum(int x)
{
int sum = 0;
while(x)
{
sum += c[x];
x -= lowbit(x);
}
return sum;
}
//令A[i] += val
void add(int x, int val)
{
while(x <= n)
{
c[x] += val;
x += lowbit(x);
}
}
int find_(int x)
{
int l=1,r=n,mid;
while(l<r)
{
mid=(l+r)>>1;
int num=sum(mid);
if(num<x)
l=mid+1;
else
r=mid;
}
return l;
}
struct node1
{
ll h,v;
} a[MAXN];
ll b[MAXN];
bool cmp(node1 x,node1 y)
{
return x.h<y.h;
}
int main()
{
int t;
t--;
cin>>t;
int kase=0;
while(t--)
{
kase++;
memset(c,0,sizeof(c));
memset(ans,0,sizeof(ans));
scanf("%lld",&n);
for(int i=1; i<=n; i++)
{
add(i,1);//代表的是人数add(i,1);
scanf("%lld%lld",&a[i].h,&a[i].v);//它的高度以及他前面或后面比他高的人数
}
sort(a+1,a+n+1,cmp);//从小到大排序;
int flag=1;
for(int i=1; i<=n; i++)
{
if(n-i-a[i].v<0)
{
flag=0;
break;
}
//不符合的情况,已经安排了前面的,若后面的>n-i就不满足了。
int p=min(a[i].v,n-i-a[i].v)+1; //前面有多少个空位,包括本身,所以+1
int pos=find_(p);//安排合适的位置
add(pos,-1);//表示这个地方已经安排了人;1代表是空位置
ans[pos]=a[i].h;//
}
printf("Case #%d:", kase);
if (flag)
{
for (int i = 1; i <= n; i++)
{
printf(" %d", ans[i]);
}
printf("\n");
}
else
printf(" impossible\n");
}
return 0;
}