樹狀數組專題(五)hdu1166
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f;
const int MN = 51000;
int n,a;
int tree[MN];
int Lowbit(int x)
{
return x&(-x);
}
void Updata(int x,int t)
{
for(int i = x ; i <= n ; i += Lowbit(i))
tree[i] += t;
}
int Getsum(int x)
{
int sum = 0;
while(x > 0)
{
sum += tree[x];
x -=Lowbit(x);
}
return sum;
}
int main()
{
int test,t1 = 0;
while(scanf("%d",&test) != EOF)
{
while(test--)
{
t1++;
printf("Case %d:\n",t1);
scanf("%d",&n);
memset(tree,0,sizeof(tree));
for(int i = 1 ; i <= n ; i++)
{
scanf("%d",&a);
Updata(i,a);
}
char order[111];
while(scanf("%s",order) && strcmp(order,"End"))
{
int beg,end;
scanf("%d%d",&beg,&end);
if(order[0] == 'A')
{
Updata(beg,end);
}
if(order[0] == 'S')
{
Updata(beg,-end);
}
if(order[0] == 'Q')
{
printf("%d\n",Getsum(end)-Getsum(beg-1));
}
}
}
}
}
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
const int inf = 0x3f3f3f;
const int MN = 51000;
int n,a;
int tree[MN];
int Lowbit(int x)
{
return x&(-x);
}
void Updata(int x,int t)
{
for(int i = x ; i <= n ; i += Lowbit(i))
tree[i] += t;
}
int Getsum(int x)
{
int sum = 0;
while(x > 0)
{
sum += tree[x];
x -=Lowbit(x);
}
return sum;
}
int main()
{
int test,t1 = 0;
while(scanf("%d",&test) != EOF)
{
while(test--)
{
t1++;
printf("Case %d:\n",t1);
scanf("%d",&n);
memset(tree,0,sizeof(tree));
for(int i = 1 ; i <= n ; i++)
{
scanf("%d",&a);
Updata(i,a);
}
char order[111];
while(scanf("%s",order) && strcmp(order,"End"))
{
int beg,end;
scanf("%d%d",&beg,&end);
if(order[0] == 'A')
{
Updata(beg,end);
}
if(order[0] == 'S')
{
Updata(beg,-end);
}
if(order[0] == 'Q')
{
printf("%d\n",Getsum(end)-Getsum(beg-1));
}
}
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.