2
5 2
1 2 3 4 5
1 5
3 5
4 1
1 1 1 1
1 2
15
12
2
一道簡單的線段樹問題
做好了建樹 ,然后搜索就行了
第一次沒想數的范圍wa了 改成longlong ac
#include <stdio.h>
#include <string.h>
struct node
{
long long a;
int l,r;
}tree[100000*4];
void build_tree(int left,int right,int root)
{
tree[root].l=left;
tree[root].r=right;
if(left==right)
{
scanf("%lld",&tree[root].a);
return ;
}
else
{
int mid=(left+right)/2;
build_tree(left,mid,root*2);
build_tree(mid+1,right,root*2+1);
tree[root].a=tree[root*2].a+tree[root*2+1].a;
}
}
void search_tree(int left,int right,int root,long long &sum)
{
if(left==tree[root].l&&right==tree[root].r)
{
sum=tree[root].a;
return ;
}
int mid=(tree[root].l+tree[root].r)/2;
if(left>mid)
search_tree(left,right,root*2+1,sum);
else if(right<=mid)
search_tree(left,right,root*2,sum);
else
{
long long sum1=0;
search_tree(left,mid,root*2,sum);
search_tree(mid+1,right,root*2+1,sum1);
sum=sum1+sum;
}
}
int main()
{
int ncase,n,m;
scanf("%d",&ncase);
while(ncase--)
{
memset(&tree,0,sizeof(&tree));
scanf("%d %d",&n,&m);
build_tree(1,n,1);
for(int i=0;i<m;i++)
{
int l1,r1;
long long sum=0;
scanf("%d %d",&l1,&r1);
search_tree(l1,r1,1,sum);
printf("%lld\n",sum);
}
}
return 0;
}
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。