hdu 1166 树状数组

  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string>
  4. using namespace std;
  5. int lowbit(int x) //make sure the set of the array 求最小幂2^k
  6. {
  7. return x&(-x);
  8. }
  9. int sum(int end ,int all[]) //solve sum 求前n 项和
  10. {
  11. int sum=0;
  12. while(end > 0)
  13. {
  14. sum+=all[end];
  15. end-=lowbit(end);
  16. }
  17. return sum;
  18. }
  19. void puls(int set, int num, int all[], int n) //array number increase or decrease 某个元素进行加法操作
  20. {
  21. while(set <= n) //网上这里有等于,这个是对的,所以一开始数组需要开大一点
  22. {
  23. all[set] += num;
  24. set += lowbit(set);
  25. }
  26. }
  27. struct data
  28. {
  29. string str;
  30. int i,j;
  31. };
  32. int main()
  33. {
  34. int T, count=0;
  35. scanf("%d",&T);
  36. while(T--)
  37. {
  38. int all[50500];
  39. int N;
  40. memset(all, 0, sizeof(all) );
  41. scanf("%d",&N);
  42. for(int i=1; i<=N; i++)
  43. /*
  44. 因为题目的关系这里从1开始输入数据,以便在计算总和时把漏掉的i加上时不会越界,并且必须从1开始“是因为跟那个“将k 化为二进制数时末尾0 的个 数”有关”
  45. */
  46. {
  47. int temp;
  48. scanf("%d",&temp);
  49. puls(i ,temp, all, N);
  50. }
  51. data temp;
  52. printf("Case %d:\n",++count);
  53. while(cin>>temp.str && temp.str!="End")
  54. {
  55. scanf("%d%d",&temp.i,&temp.j);
  56. if(temp.str =="Query" )
  57. {
  58. printf("%d\n",sum(temp.j,all)-sum(temp.i-1,all) );
  59. /*
  60. i-1 pay attention
  61. the problem describe solve j-i ( Query i j ,i和j为正整数,i<=j,表示询问第i到第j个营地的总人数;)
  62. so all[i] could be ignore !
  63. */
  64. }
  65. if(temp.str == "Add" )
  66. {
  67. puls(temp.i ,temp.j, all, N);
  68. }
  69. if(temp.str =="Sub")
  70. puls(temp.i ,-temp.j, all, N);
  71. }
  72. }
  73. return 0;
  74. }
  75. /*
  76. 第一行一个整数T,表示有T组数据。
  77. 每组数据第一行一个正整数N(N<=50000),表示敌人有N个工兵营地,接下来有N个正整数,第i个正整数ai代表第i个工兵营地里开始时有ai个人(1<=ai<=50)。
  78. 接下来每行有一条命令,命令有4种形式:
  79. (1) Add i j,i和j为正整数,表示第i个营地增加j个人(j不超过30)
  80. (2)Sub i j ,i和j为正整数,表示第i个营地减少j个人(j不超过30);
  81. (3)Query i j ,i和j为正整数,i<=j,表示询问第i到第j个营地的总人数;
  82. (4)End 表示结束,这条命令在每组数据最后出现;
  83. 每组数据最多有40000条命令
  84. Output
  85. 对第i组数据,首先输出“Case i:”和回车,
  86. 对于每个Query询问,输出一个整数并回车,表示询问的段中的总人数,这个数保持在int以内。
  87. Sample Input
  88. 1
  89. 10
  90. 1 2 3 4 5 6 7 8 9 10
  91. Query 1 3
  92. Add 3 6
  93. Query 2 7
  94. Sub 10 2
  95. Add 6 3
  96. Query 3 10
  97. End
  98. Sample Output
  99. Case 1:
  100. 6
  101. 33
  102. 59
  103. */





附件列表

     

    posted @ 2015-01-29 15:32  sober_reflection  阅读(114)  评论(0)    收藏  举报