本文共 3074 字,大约阅读时间需要 10 分钟。
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 85071 Accepted Submission(s): 35909
1 /* 使用树状数组,借用树状数组的快速求和的方式可以将求和的复杂度降低到 2 * log(N)。 3 */ 4 5 #include6 #include 7 #include 8 9 using namespace std;10 11 #define MAXN 5000512 13 int seq[MAXN];14 int MaxVal;15 int ornum[MAXN];16 17 int lowbit(int num)18 {19 return num & (num^(num-1));20 }21 22 int calsum(int m)23 {24 int csum = 0;25 while (m > 0)26 {27 csum += seq[m];28 m -= lowbit(m);29 }30 return csum;31 }32 33 int update(int idx, int num)34 {35 while (idx <= MaxVal)36 {37 seq[idx] += num;38 idx += lowbit(idx);39 }40 }41 42 int main(void)43 {44 int T;45 char str[10];46 int a, b;47 scanf("%d", &T);48 for (int i = 1; i <= T; i++)49 {50 // 尤其要注意这里对数组的清空操作。51 memset(seq, 0, sizeof(seq));52 memset(ornum, 0, sizeof(ornum));53 scanf("%d", &MaxVal);54 for (int j = 1; j <= MaxVal; j++)55 {56 scanf("%d", &ornum[j]);57 update(j, ornum[j]);58 }59 printf("Case %d:\n", i);60 while(~scanf("%s", str))61 {62 if (str[0] == 'E')63 break;64 scanf("%d %d",&a, &b);65 // printf("%s\n%d\t%d\n", str, a, b);66 if (str[0] == 'Q')67 {68 // 其实这里为什么还有一个a-1,其实还有待思考69 printf("%d\n", calsum(b)-calsum(a-1));70 }71 else if (str[0] == 'A')72 {73 update(a, b);74 }75 else if (str[0] == 'S')76 {77 update(a, -b);78 }79 }80 }81 return 0;82 }
转载地址:http://osjko.baihongyu.com/