1. 程式人生 > 實用技巧 >Lost Cows(線段樹) POJ - 2182

Lost Cows(線段樹) 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.


題意:給出n頭牛前面有多少頭比他編號少的數目,求出原來的牛的編號,


#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
#include<stdio.h>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include <sstream>
#include
<vector> #include<cmath> #include<stack> #include<time.h> #include<ctime> using namespace std; #define inf 1<<30 #define eps 1e-7 #define LD long double #define LL long long #define maxn 100000005 int tree[maxn] = {}; int a[maxn] = {}; int b[maxn] = {}; void buildTree(int step,int L,int R)//建樹 { if (L == R) { tree[step] = 1; return; } int mid = (L + R) >> 1; buildTree(step * 2, L, mid); buildTree(step * 2 + 1, mid + 1, R); tree[step] = tree[step * 2] + tree[step * 2 + 1]; } int search(int step, int L, int R, int num) { tree[step]--;//更新,當前位置減一 if (L == R) { return L; } int mid = (L + R) / 2; if (num <= tree[step * 2])//在左子樹範圍 search(step * 2, L, mid, num); else search(step * 2 + 1, mid + 1, R, num-tree[step*2]);//在右子樹範圍,減去左子樹的個數 } int main() { int n; scanf("%d", &n); buildTree(1, 1, n); for (int i = 2; i <= n; i++) { scanf("%d", &a[i]); } a[1] = 0; for (int i = n; i >= 1; i--)//從後往前找,只有最後一個是確定的 { b[i] = search(1, 1, n, a[i] + 1);//查詢編號時要加一 } for (int i = 1; i <= n; i++) { printf("%d\n", b[i]); } }