最近开始入门线段树,先从hdu1166开始把。
题目链接:点击打开链接
线段树适合多次查询,更新节点等操作,并不适合删除操作,查询时间复杂度为O(logn);
这道线段树的入门题在网上看了很久的代码,发现难点并不在建树上面,建树的操作就是把要操作的值分为许多的单位区间,并且保存到树的叶节点中,向上可以表示不同区间内要查询的结果,这里需要用到递归建树。
然后是关于线段树的查询和更新,这里还有些糊涂,先慢慢想着理解下吧。
下面是这道题的代码:移位运算符写的太多,看上去很疲惫,最好还是用其他方法表示。(951ms)
#include <cstdio>
#include <string>
#include <iostream>
using namespace std;
int num[50050];
struct Node
{
int left ,right ,sum;
}b[50050*3];
void Build(int left,int right,int i) //i代表起始节点也就是当前节点
{
b[i].left = left;
b[i].right = right;
if(left == right){
b[i].sum = num[left]; //每个叶节点代表一个单位区间
return ;
}
Build(left , (left+right)>>1 ,i<<1);
Build(((left+right)>>1)+1,right,i<<1|1);
b[i].sum = b[i<<1].sum+b[i<<1|1].sum;
}
void Add(int id,int tmp,int i)
{
if(b[i].left == b[i].right){ //叶节点的更新
b[i].sum = b[i].sum+tmp;
return ;
}
else{
b[i].sum = b[i].sum+tmp;
if(id<=b[i<<1].right) Add(id,tmp,i<<1); //id在左区间内
else Add(id,tmp,i<<1|1); //id在右区间内
}
}
int Query(int left ,int right,int i)
{
if(b[i].left == left&&b[i].right == right){
return b[i].sum;
}
if(right <= ((b[i].left+b[i].right)>>1)) return Query(left,right,i<<1);
else if(left > ((b[i].left+b[i].right)>>1)) return Query(left,right,i<<1|1);
else return Query(left,(b[i].left+b[i].right)>>1,i<<1)+Query(((b[i].left+b[i].right)>>1)+1,right,i<<1|1);
}
int main()
{
//cout<<"hello world!"<<endl;
int t;
//ios::sync_with_stdio(true);
cin>>t;
for(int i = 1;i <= t;i++){
int n;
cin>>n;
for(int j = 1;j <= n;j++){
cin>>num[j];
}
Build(1,n,1);
cout<<"Case "<<i<<":"<<endl;
string cmd;
int x,y;
while(cin>>cmd&&cmd[0]!='E'){
cin>>x>>y;
if(cmd[0] == 'Q')
cout<<Query(x,y,1)<<endl;
else if(cmd[0] == 'A')
Add(x,y,1);
else if(cmd[0] == 'S')
Add(x,-y,1);
}
}
return 0;
}