Language:Default
Lost Cows
Description
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 |
题目大意:
有n头牛,编号为1~N,现在这些牛无序的站成一队,现在除了第一头牛外,都知道每头牛前面有多少编号比他小的牛,让你求出现在队伍中每头牛的编号。
输入:
第一行输入n
接下来n-1行表示从第二头牛开始到最后一头牛的前面有多少头编号比他本身的编号小的牛;
思路:
最后一头牛前面有k头编号比他小的,所以 最后一头牛的编号是k+1,然后删除k+1, 倒数第二头可以看成 倒数第一头, 以此类推,但是删除操作,用数组模拟的话每次删除操作的复杂度是O(n),总的复杂度是O(n*n)会超时,用线段树进行每次删除操作的复杂度是O(nlogn);
AC 代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#define maxn 10001
using namespace std;
struct {
int lc;
int rc;
int len;
}tree[maxn<<2];
int num[maxn], ans[maxn];
void build(int l,int r,int rt) {
cout << "l : " << l << " r: " << r << " rt:"<< rt << endl;
tree[rt].lc = l;
tree[rt].rc = r;
tree[rt].len = r - l + 1;
if (l == r) return;
build(l, (l + r) >> 1, rt << 1);
build(((l + r) >> 1) + 1 , r, (rt << 1) + 1);
}
int query(int rt, int k) {
tree[rt].len--;
if (tree[rt].lc == tree[rt].rc) return tree[rt].lc;
else if (k <= tree[rt * 2].len)
return query(rt * 2, k);
else
return query(rt * 2 + 1, k - tree[rt << 1].len);
}
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif
int n;
while (cin >> n) {
for (int i = 2; i <= n; i++) {
cin >> num[i];
}
num[1] = 0;
build(1, n, 1);
for (int i = n; i > 0; i--) {
ans[i] = query(1, num[i] + 1);
}
for (int i = 1; i <= n; i++) {
cout << ans[i] << endl;
}
}
return 0;
}