Lost Cows
N (2 <= N <= 8,000) cows have unique brands in the range 1..N. In a spectacular display of poor judgment, they visited the neighborhood 'watering hole' and drank a few too many beers before dinner. When it was time to line up for their evening meal, they did not line up in the required ascending numerical order of their brands.
Regrettably, FJ does not have a way to sort them. Furthermore, he's not very good at observing problems. Instead of writing down each cow's brand, he determined a rather silly statistic: For each cow in line, he knows the number of cows that precede that cow in line that do, in fact, have smaller brands than that cow.
Given this data, tell FJ the exact ordering of the cows.
Input
* Line 1: A single integer, N
* Lines 2..N: These N-1 lines describe the number of cows that precede a given cow in line and have brands smaller than that cow. Of course, no cows precede the first cow in line, so she is not listed. Line 2 of the input describes the number of preceding cows whose brands are smaller than the cow in slot #2; line 3 describes the number of preceding cows whose brands are smaller than the cow in slot #3; and so on.
Output
* Lines 1..N: Each of the N lines of output tells the brand of a cow in line. Line #1 of the output tells the brand of the first cow in line; line 2 tells the brand of the second cow; and so on.
Sample Input
5 1 2 1 0
Sample Output
2 4 5 3 1
题意:一共5头牛,排成一排,知道2-5每头牛前面产量比他少的牛的个数分别为:1,2,1,0。求队列里的五头牛对应的产量排名。
思路:跟这个题挺像的Buy Tickets(线段树+逆序),这个题也是用到了逆序,因为队伍中存的是当前位置前有多少产量比他少的牛,后面的优先级是要高于前面的。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<utility>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#define maxn 8005
#define INF 0x3f3f3f3f
#define LL long long
#define ULL unsigned long long
#define E 1e-8
#define mod 1000000007
#define P pair<int,int>
#define MID(l,r) (l+(r-l)/2)
#define lson(o) (o<<1) //o*2
#define rson(o) (o<<1|1) //o*2+1
using namespace std;
int a[maxn];
int ans[maxn];
struct node{
int l,r,num;
}tree[maxn<<2];
void build(int o,int l,int r)
{
tree[o].l = l;
tree[o].r = r;
if(l == r){
tree[o].num = 1;
return ;
}
int m = MID(l,r);
int lc = lson(o),rc = rson(o);
build(lc,l,m);
build(rc,m+1,r);
tree[o].num = tree[lc].num + tree[rc].num;
}
void update(int o,int p,int v)
{
if(tree[o].l == tree[o].r){
ans[v] = tree[o].l;
tree[o].num = 0;
return ;
}
int lc = lson(o),rc = rson(o);
if(p <= tree[lc].num) update(lc,p,v); //这里两步是重点
else update(rc,p-tree[lc].num,v); //p - tree[lc].num
tree[o].num = tree[lc].num + tree[rc].num;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF){
build(1,1,n);
a[1] = 1;
for(int i=2;i<=n;++i){
scanf("%d",&a[i]);
a[i]++; //不能忽略
}
for(int i=n;i>=1;--i){
update(1,a[i],i);
}
for(int i=1;i<=n;++i){
printf("%d\n",ans[i]);
}
}
return 0;
}