题目:http://poj.org/problem?id=3468
超时代码:
#include<bits/stdc++.h>
#define INF 1e18
#define inf 1e9
#define min(a,b) a<b?a:b
#define max(a,b) a>b?a:b
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define IOS ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std ;
typedef long long ll;
typedef unsigned long long ull;
const ll _max = 100000+500;
ll a[_max];
int n,m;
inline int lowbit(int x){
return x&(-x);
}
inline int sum(int i){
ll sum = 0;
while(i > 0){
sum += a[i];
i -= lowbit(i);
}
return sum;
}
inline void update(int i,int x){
while(i <= n ){
a[i] += x;
i += lowbit(i);
}
}
int main(){
IOS;
while(cin>>n>>m){
memset(a,0,sizeof(a));
ll val;
for(int i = 1 ; i <= n ; i++){
cin >> val;
update(i,val);
}
char cnt;
int l,r,x;
for(int i = 1 ; i <= m ; i++){
cin >> cnt;
if(cnt == 'Q'){
cin>>l>>r;
cout<<sum(r)-sum(l-1)<<endl;
}
if(cnt == 'C'){
cin>>l>>r>>x;
for(int t = l ; t <= r ; t++)
update(t,x);
}
}
}
return 0;
}
这段代码在处理更新数据上花费了大量的时间。当时我只知道用线段是怎么处理。后来查看了别人的代码,发现了一个很好的处理方法。和线段树相似的是,都要开第二个数组用以标记。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
// head
struct BIT {
#define T LL
static const int N = 500005;
T tree[N] ;
inline int lowbit(int x) {
return x&(-x);
}
void add(int x, T add, int n) {
for (int i = x; i <= n; i += lowbit(i)) {
tree[i] += add;
}
}
T sum(int x) {
T ans = 0;
for (int i = x; i > 0; i -= lowbit(i)) {
ans += tree[i];
}
return ans;
}
void clear(int n) {
for (int i = 1; i <= n; i++) {
tree[i] = 0;
}
}
#undef T
};
BIT bt0, bt1;
char s[5];
int main() {
int n, m, a, b, c, x;
while (scanf("%d%d", &n, &m) == 2) {
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
bt0.add(i, x, n);
}
for (int i = 0; i < m; i++) {
scanf("%s%d%d", s, &a, &b);
if (s[0] == 'Q') {
LL ans = bt0.sum(b) - bt0.sum(a-1);
ans += b * bt1.sum(b) - (a-1) * bt1.sum(a-1);
printf("%I64d\n", ans);
} else {
scanf("%d", &c);
bt0.add(b+1, LL(b) * c, n);
bt0.add(a, -LL(a-1) * c, n);
bt1.add(b+1, -c, n);
bt1.add(a, c, n);
}
}
bt0.clear(n);
bt1.clear(n);
}
return 0;
}