您的位置:首页 > 其它

UVA 12086 (树状数组)

2016-08-16 15:40 381 查看
题目网址:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3238

题意:给你n个数,有两种操作,M a b为查询[a,b]这个区间内的数的和,S a b为把第a个数修改成b,END结束。

用树状数组和线段树都可以做。

附上树状数组代码:

<span style="font-size:18px;">#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

#define mem(a,b) memset(a,b,sizeof(a))
#define lf(i,n) for(int i=1;i<=n;i++)
#define sc(a) scanf("%d",&a)
#define nsc(a,b) scanf("%d %d",&a,&b)
#define pr(a) printf("%d\n",a)
#define inf 0x3f3f3f3f

int n,num[200010],c[200010];

int lowbit(int x)
{
return x&(-x);
}

int Sum(int x)
{
int sum=0;
while(x>0)
{
sum+=c[x];
x-=lowbit(x);
}
return sum;
}

void Setnum(int e,int x) //修改第e个数的值。
{
e-=num[x];
num[x]+=e;
while(x<=n)
{
c[x]+=e;
x+=lowbit(x);
}
return ;
}

int main()
{
char s[4];
int a,b,count1=1;
while(~sc(n)&&n)
{
mem(c,0);
lf(i,n)
{
sc(num[i]);
for(int j=i; j>i-lowbit(i); j--) //初始化c数组
c[i]+=num[j];
}
if(count1>1)
printf("\n");
printf("Case %d:\n",count1++);
while(1)
{
scanf("%s",s);
if(!strcmp(s,"END"))
break;
nsc(a,b);
if(s[0]=='M')
printf("%d\n",Sum(b)-Sum(a-1));
else if(s[0]=='S')
{
Setnum(b,a);
}
}
}
return 0;
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: