# 【HDU1166】敌兵布阵【两种AC解法：线段树、BIT】

C国的死对头A国这段时间正在进行军事演习，所以C国间谍头子Derek和他手下Tidy又开始忙乎了。A国在海岸线沿直线布置了N个工兵营地,Derek和Tidy的任务就是要监视这些工兵营地的活动情况。由于采取了某种先进的监测手段，所以每个工兵营地的人数C国都掌握的一清二楚,每个工兵营地的人数都有可能发生变动，可能增加或减少若干人手,但这些都逃不过C国的监视。

#include <iostream>
#include <string>
#include <memory.h>

using namespace std;

const int LIM = 50010;
const int SIZE = 131100;
int data[LIM];
int STree[SIZE];
int n;

void construct();
void updateFec(int ss, int se, int si, int idx, int diff);
void update(int idx, int diff);
int getSumFec(int ss, int se, int ps, int pe, int idx);
int getSum(int from, int to);

void construct() {
memset(STree, 0, sizeof STree);
for (int i = 1; i <= n; i++) {
updateFec(1, n, i, 0, data[i]);
}
}

void updateFec(int ss, int se, int si, int idx, int diff) {
if (si < ss || si > se || se < ss)
return ;
STree[idx] += diff;
if (ss != se) {
int mid = (ss + se) >> 1;
updateFec(ss, mid, si, idx * 2 + 1, diff);
updateFec(mid + 1, se, si, idx * 2 + 2, diff);
}
}

void update(int idx, int diff) {
data[idx] += diff;
updateFec(1, n, idx, 0, diff);
}

int getSumFec(int ss, int se, int ps, int pe, int idx) {
if (ss >= ps && se <= pe)
return STree[idx];

if (se < ps || ss > pe)
return 0;

//not the leaf
if (ss != se) {
int mid = (ss + se) >> 1;
return getSumFec(ss, mid, ps, pe, idx * 2 + 1)
+ getSumFec(mid + 1, se, ps, pe, idx * 2 + 2);

}
}

int getSum(int from, int to) {
return getSumFec(1, n, from, to, 0);
}

int main(void) {
int t;
scanf("%d", &t);
for (int k = 1; k <= t; k++) {
printf("Case %d:\n", k);
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", data + i);
construct();
string op;
int t1, t2;
while (cin >> op && op[0] != 'E') {
scanf("%d%d", &t1, &t2);
switch(op[0]) {
case 'S':
update(t1, -t2);
break;
case 'A':
update(t1, t2);
break;
case 'Q':
cout << getSum(t1, t2) << endl;
break;
}
}
}
return 0;
}

#include <iostream>
#include <string>
#include <memory.h>

using namespace std;

const int LIM = 50010;
int data[LIM];
int BITree[LIM];
int n;

void construct() {
for (int i = 1; i <= n; i++) {
for (int j = i; j <= n; j += j & (-j)) {
BITree[j] += data[i];
}
}
}

void update(int idx, int diff) {
data[idx] += diff;
for (int i = idx; i <= n; i += i & (-i)) {
BITree[i] += diff;
}
}

int getSum(int idx) {
int ret = 0;
for (int i = idx; i > 0; i -= i & (-i)) {
ret += BITree[i];
}
return ret;
}

inline int getSum(int from, int to) {
return getSum(to) - getSum(from - 1);
}

int main(void) {
int t;
scanf("%d", &t);
for (int k = 1; k <= t; k++) {
printf("Case %d:\n", k);
scanf("%d", &n);
for (int i = 1; i <= n; i++)
scanf("%d", data + i);
memset(BITree, 0, sizeof BITree);
construct();
string op;
int t1, t2;
while (cin >> op && op[0] != 'E') {
scanf("%d%d", &t1, &t2);
switch(op[0]) {
case 'S':
update(t1, -t2);
break;
case 'A':
update(t1, t2);
break;
case 'Q':
cout << getSum(t1, t2) << endl;
break;
}
}
}
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120