树状数组_二分_POJ-2182

题目链接:http://poj.org/problem?id=2182

这题似乎可以有多解,但题目里似乎没有specialjudge

本题解法较为简单,注意到每次可以确定队尾的元素,在剩下的未确定的元素中排第几。

至于值为多少就可以用二分和树状数组来解决。

 1 #include<cstdio>

 2 #include<cstdlib>

 3 #include<cstring>

 4 #include<algorithm>

 5 using namespace std;

 6 #define lowbit(a) ((a)&(-a))

 7 #define max(a, b) ((a)>(b)?(a):(b))

 8 #define min(a, b) ((a)<(b)?(a):(b))

 9 #define MAXN 10010

10 #define PI 3.1415926

11 #define E 2.718281828

12 #define INF 0x777777f

13 typedef long long LL;

14 

15 struct BIT{

16     #define bMAXN 10010

17     int bCnt, sum[bMAXN];

18     void add(int p, int v){

19         for ( ; p <= bCnt; p += lowbit(p))

20             sum[p] += v;

21     }

22     int query(int p){

23         int ret = 0;

24         for ( ; p; p -= lowbit(p))

25             ret += sum[p];

26         return ret;

27     }

28 } t;

29 int n, a[MAXN], ans[MAXN];

30 

31 int find(int v){

32     int l = 1, r = n, mid;

33     while (l <= r){

34         mid = (l+r)>>1;

35         int tmp = t.query(mid);

36         if (tmp < v) l = mid+1;

37         if (tmp >= v) r = mid-1;    //每次找到最左边的那个,防止访问已被删除的节点

38     } return l;

39 }

40 int main(){

41     scanf("%d", &n); t.bCnt = n;

42     for (int i = 2; i <= n; i++) scanf("%d", &a[i]);

43     for (int i = 1; i <= n; i++) t.add(i, 1);    //初始化

44     for (int i = n; i >= 1; i--){

45         ans[i] = find(a[i]+1);

46         t.add(ans[i], -1);

47     }

48     for (int i = 1; i <= n; i++) printf("%d\n", ans[i]);

49     return 0;

50 }

你可能感兴趣的:(树状数组)