POJ 2828 Buy Tickets(树状数组+二分)

题目链接

看了别人思路,逆序插入,然后就会发现只要为留出pos[i]个位置就行了。树状数组+二分求下界就好了。

 1 #include <stdio.h>

 2 #include <string.h>

 3 #include <algorithm>

 4 #include <iostream>

 5 using namespace std;

 6 #define N 200011

 7 int pos[N];

 8 int p[N],n;

 9 struct node

10 {

11     int val;

12     int id;

13 }num[N];

14 int lowbit(int t)

15 {

16     return t&(-t);

17 }

18 void insert(int t,int d)

19 {

20     while(t <= n)

21     {

22         p[t] += d;

23         t += lowbit(t);

24     }

25 }

26 int getsum(int t)

27 {

28     int sum = 0;

29     while(t > 0)

30     {

31         sum += p[t];

32         t -= lowbit(t);

33     }

34     return sum;

35 }

36 int cmp(node a,node b)

37 {

38     return a.id < b.id;

39 }

40 int main()

41 {

42     int i,str,end,temp,mid;

43     while(scanf("%d",&n)!=EOF)

44     {

45         for(i = 0;i < n;i ++)

46         {

47             scanf("%d%d",&pos[i],&num[i].val);

48             p[i] = 0;

49         }

50         for(i = 0;i < n;i ++)

51         {

52             insert(i+1,1);

53         }

54         for(i = n-1;i >= 0;i --)

55         {

56             str = 1;

57             end = n;

58             while(str < end)

59             {

60                 mid = (str+end)/2;

61                 temp = getsum(mid);

62                 if(temp < pos[i]+1)//求上界

63                 str = mid + 1;

64                 else

65                 end = mid;

66             }

67             num[i].id = str;

68             insert(str,-1);

69         }

70         sort(num,num+n,cmp);

71         for(i = 0;i < n;i ++)

72         {

73             if(i == 0)

74             printf("%d",num[i].val);

75             else

76             printf(" %d",num[i].val);

77         }

78         printf("\n");

79     }

80     return 0;

81 }

 

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