2017年5月7日
题目来源:
http://acm.hdu.edu.cn/showproblem.php?pid=1166
分析:
每次只修改一个点,求的是一个区间的内容
代码如下:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
const int maxn = 99999;
int c[maxn],a[maxn];
int n;
int x1,x2;
int lowbit(int x)
{
return (-x)&x;
}
void update(int x, int num)
{
while(x <= n)
{
c[x] += num;
x += lowbit(x);
}
}
int sum(int x)
{
int s = 0;
while(x > 0)
{
s += c[x];
x -= lowbit(x);
}
return s;
}
int Getsum(int i , int j )
{
return sum(j) - sum(i-1);
}
int main()
{
int T;
cin >> T;
for(int i = 1; i <= T; i++)
{
memset(a,0,sizeof(a));
memset(c,0,sizeof(c));
cout << "Case "<<i <<":"<< endl;
cin >> n;
for(int j = 1; j <= n ; j++)
{
cin >> a[j];
update(j,a[j]);
}
string oper;
while(cin >> oper)
{
if(oper == "End")
break;
cin >> x1 >> x2;
if(oper == "Query")
{
cout << Getsum(x1,x2) << endl;
}
if(oper == "Add")
{
a[x1] += x2;
update(x1,x2);
}
if(oper == "Sub")
{
a[x1] -= x2;
update(x1,-x2);
}
}
}
return 0;
}