poj 2828 Buy Tickets 【线段树点更新】

淡淡的烟草味﹌ 2022-08-13 13:57 125阅读 0赞

题目:poj 2828 Buy Tickets

题意:有n个人排队,每个人有一个价值和要插的位置,然后当要插的位置上有人时所有的人向后移动一位当这个插入到这儿,如果没有直接插进去。

分析:分析发现直接插入移动的话花时间太多,我们可不可以用逆向思维。从后往前来,因为最后一个位置是肯定能确定的,而其他的则插入空的第某个位置。

比如第一组样例:

  1. 4
  2. 0 77
  3. 1 51
  4. 1 33
  5. 2 69

开始时候位置都为空 编号0 1 2 3

首先从最后一个来2 69

第二个位置空,则可以直接放

然后编号变为0 1 69 2

接着放1 33

编号变为 0 33 69 1

然后放1 51

编号变为0 33 69 51

然后放最后一个0 77

则最后结果为 77 33 69 51

可以发现该怎么搞了,就是直接用线段树来维护区间上的值,然后选择插入相应的位置即可。

AC代码:

  1. #include <cstdio>
  2. #include <vector>
  3. #include <iostream>
  4. using namespace std;
  5. typedef long long LL ;
  6. const int N = 220000;
  7. struct Node
  8. {
  9. int l,r;
  10. int val,num;
  11. };
  12. Node tree[5*N];
  13. void build(int o,int l,int r)
  14. {
  15. tree[o].l = l,tree[o].r = r;
  16. if(l==r)
  17. {
  18. tree[o].val = 1;
  19. return ;
  20. }
  21. int mid = (l+r)/2;
  22. build(o+o,l,mid);
  23. build(o+o+1,mid+1,r);
  24. tree[o].val = tree[o+o].val + tree[o+o+1].val;
  25. }
  26. void update(int o,int num,int val)
  27. {
  28. //printf("%d %d %d %d\n",o,tree[o].l,tree[o].r,tree[o].val);
  29. if(tree[o].l==tree[o].r)
  30. {
  31. tree[o].num = val;
  32. tree[o].val = 0;
  33. return ;
  34. }
  35. if(tree[o+o].val>=num)
  36. update(o+o,num,val);
  37. else
  38. update(o+o+1,num-tree[o+o].val,val);
  39. tree[o].val = tree[o+o].val + tree[o+o+1].val;
  40. }
  41. vector<int> ans;
  42. void Yougth(int o)
  43. {
  44. if(tree[o].l==tree[o].r)
  45. {
  46. ans.push_back(tree[o].num);
  47. return ;
  48. }
  49. Yougth(o+o);
  50. Yougth(o+o+1);
  51. }
  52. pair <int,int> p[N];
  53. int main()
  54. {
  55. //freopen("Input.txt","r",stdin);
  56. int n;
  57. while(~scanf("%d",&n))
  58. {
  59. build(1,1,n);
  60. for(int i=0;i<n;i++)
  61. {
  62. int x,y;
  63. scanf("%d%d",&x,&y);
  64. x++;
  65. p[i] = make_pair(x,y);
  66. }
  67. for(int i=n-1;i>=0;i--)
  68. update(1,p[i].first,p[i].second);
  69. Yougth(1);
  70. for(int i=0;i<ans.size();i++)
  71. printf("%d%c",ans[i],i==(ans.size()-1)?'\n':' ');
  72. ans.clear();
  73. }
  74. return 0;
  75. }

发表评论

表情:
评论列表 (有 0 条评论,125人围观)

还没有评论,来说两句吧...

相关阅读