int lowbit(int x)
{
return x - (x&(x-1)); // x&(-x)
}
// 在第i个数上加上value
void add(int i, int value)
{
while (i<= N)
{
c[i] += value;
i += lowbit(i);
}
}
// 取出前i个元素之和
int sum(int i)
{
int sum = 0;
while (i>0)
{
sum += c[i];
i -= lowbit(i);
}
return sum;
}
Input
Output
Sample Input
1
10
1 2 3 4 5 6 7 8 9 10
Query 1 3
Add 3 6
Query 2 7
Sub 10 2
Add 6 3
Query 3 10
End
Sample Output
Case 1:
6
33
59
#include
using namespace std;
const int maxn = 50005;
int N, c[maxn];
int lowbit(int x)
{
return x - (x&(x-1)); // x&(-x)
}
// 在第i个数上加上value
void add(int i, int value)
{
while (i<= N)
{
c[i] += value;
i += lowbit(i);
}
}
// 取出前i个元素之和
int sum(int i)
{
int sum = 0;
while (i>0)
{
sum += c[i];
i -= lowbit(i);
}
return sum;
}
int main()
{
int t, Case = 0;
cin >> t;
while (t--)
{
printf("Case %d:\n", ++Case);
scanf("%d", &N);
memset(c, 0, sizeof(c));
int t;
for (int i = 1; i <= N; ++i) {
scanf("%d", &t);
add(i, t);
}
char command[15];
int x, y;
while (~scanf("%s", command) && command[0]!='E')
{
scanf("%d%d", &x, &y);
if (command[0] == 'Q')
{
int res = sum(y)-sum(x-1);
cout << res << endl;
}
else if(command[0] == 'A')
{
add(x, y);
}
else add(x, -y);
}
}
return 0;
}
Input
Output
Sample Input
3
1 1
2 2
3 3
3
1 1
1 2
1 3
0
Sample Output
1 1 1
3 2 1
#include
using namespace std;
int N;
const int maxn = 100005;
int c[maxn];
int lowbit(int i)
{
return i&(-i);
}
void add(int i, int value)
{
while (i<=N)
{
c[i] += value;
i += lowbit(i);
}
}
int sum(int i)
{
int sum = 0;
while(i>0)
{
sum += c[i];
i -= lowbit(i);
}
return sum;
}
int main()
{
while (scanf("%d", &N) && N!=0) {
int a, b;
memset(c, 0, sizeof(c));
for (int i = 1; i <= N; ++i) {
cin >> a >> b;
add(a, 1); // 将[a,N]区间全加1
add(b + 1, -1); // 将[b+1, N]区间全减一
// 这样就实现了区间[a,b]上的涂色
}
for (int i = 1; i <= N; ++i) {
cout << sum(i) << " ";
}
cout << endl;
}
return 0;
}
问题描述
输入格式
输出格式
样例输入
5 3
1 2 3 4 5
2 1 5
1 1 3 2
2 1 5
样例输出
15
14
评测用例规模与约定
#include
using namespace std;
const int maxn = 100005;
int N;
int a[maxn]; // 存放原始数据
long long c[maxn]; // 存放树状数组
int lowbit(int x)
{
return x&(-x);
}
void add(int i, int value)
{
while (i<=N)
{
c[i] += value;
i += lowbit(i);
}
}
long long sum(int i)
{
long long sum = 0;
while (i>0)
{
sum += c[i];
i -= lowbit(i);
}
return sum;
}
int main()
{
int M;
cin >> N >> M;
for (int i = 1; i <= N; ++i) {
cin >> a[i];
add(i, a[i]);
}
for (int i = 0; i < M; ++i) {
int opt, l, r, v;
cin >> opt >> l >> r;
if (opt==2)
{
cout << sum(r)-sum(l-1) << endl;
}
else
{
cin >> v;
if (v==1) continue; // 不处理除以1这种情况会超时
for (int j = l; j <= r; ++j)
{
if (a[j]>=v && a[j]%v==0) // 不加上a[j]>v会超时
{
add(j, -(a[j]-a[j]/v)); // 用加法代替除法a[j]/v = a[j]-(a[j]-a[j]/v)
a[j] = a[j]/v;
}
}
}
}
return 0;
}