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>
题意:给你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>
相关文章推荐
- emguCv3.x 实现字符分割,轮廓检测
- 递归:排成一条线的硬币博弈问题
- Windows环境下的MySQL编码方式修改
- Jmeter之逻辑控制器(Logic Controller)
- 虚拟内存vs物理内存
- 【golang】go-ConcurrentMap实现
- 今天学会了MarkDown语法,很简单不过很实用
- Xcode中svn文件后缀符号含义
- Netflix OSS、Spring Cloud还是Kubernetes? 都要吧!
- 持续交付系列之一:无人工干预持续交付
- Q42:翻转单词顺序VS左旋转字符串
- WPF自定义Main函数
- rowcommand事件中获取控件
- LeetCode:Add Digits - 非负整数各位相加
- 搭建持续集成接口测试平台(Jenkins+Ant+Jmeter)
- 找女朋友【快速排序】
- linux下上传代码到github
- 51nod 1416 两点(DFS)
- 读取指定行数文件内容并显示
- 关于内存泄漏的总结性报告