POJ-2182-线段树模板题

题目描述

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.

1
2
3
4
5
5
1
2
1
0

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.

1
2
3
4
5
2
4
5
3
1

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
1. 左移乘法,右移除法
2. 移1位表示 *or/2,移2位表示 *or/4
3. 移位运算一定要加括号
*/
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4+2;

struct Node{
// len表示当前节点的长度
int l, r, len;
}tree[N*4];
int pre[N], ans[N];

// 建立线段树
void build_tree(int root, int left, int right){
tree[root].l = left; tree[root].r = right;
tree[root].len = right-left+1;
if(left == right) return;

build_tree(root<<1, left, (left+right)>>1);
build_tree((root<<1)+1, ((left+right)>>1)+1, right);
}

// 寻找当前节点下第k大的元素
int quary(int root, int k){
tree[root].len--;

if(tree[root].l == tree[root].r) return tree[root].l;

// 如果左子树节点数量小于k,则从右子树寻找第 k-tree[root<<2].len 个元素
if(tree[root<<1].len<k) return quary((root<<1)+1, k-tree[root<<1].len);

// 如果大于k,表示左子树节点数量足够,继续从左子树寻找
if(tree[root<<1].len >= k) return quary(root<<1, k);
}

int main(){
int n;

cin >> n;
for(int i=0;i<n;i++) scanf("%d", &pre[i]);

build_tree(1, 1, n);

for(int i=n-1; i>=0; i--){
ans[i] = quary(1, pre[i]+1);
}

for(int i=0;i<n;i++) cout << ans[i] << " ";
cout << endl;

system("pause");
return 0;
}

/*
5
0 1 2 1 0
*/

2182 -- Lost Cows (poj.org)