第一个功能怎么才能靠前缀和实现?(暴力模拟TLE了)
代码:
#include <iostream>
using namespace std;
#define maxn 500010
long long n , m , ans ;
long long c[maxn] ;
long long lowbit(int x){
return x & -x ;
}
void add(long long x , long long v){
while(x <= n)
{
c[x] += v ;
x += lowbit(x);
}
return ;
}
long long sum(long long x){
long long ans = 0 ;
while(x != 0){
ans += c[x] ;
x -= lowbit(x);
}
return ans ;
}
int main(){
ios::sync_with_stdio(0);
cin>>n>>m;
for(int i = 1 ; i <= n ; i++){
long long a ; cin>>a ; add(i , a) ;
}
while(m--){
int opt ; cin>>opt;
if(opt == 1){
int a , b , k ;
cin>>a>>b>>k;
add(a , k);
add(b , -k);
}
if(opt == 2){
int n ; cin>>n;
cout<<sum(n) - sum(n - 1) <<endl;
}
}
return 0;
}
%%%