HDU6315 Naive Operations(线段树)
题目:
In a galaxy far, far away, there are two integer sequence a and b of length n.
b is a static permutation of 1 to n. Initially a is filled with zeroes.
There are two kind of operations:
- add l r: add one for al,al+1…ar
- query l r: query ∑ri=l⌊ai/bi⌋
Input:
There are multiple test cases, please read till the end of input file.
For each test case, in the first line, two integers n,q, representing the length of a,b and the number of queries.
In the second line, n integers separated by spaces, representing permutation b.
In the following q lines, each line is either in the form ‘add l r’ or ‘query l r’, representing an operation.
1≤n,q≤100000, 1≤l≤r≤n, there’re no more than 5 test cases.
Output
Output the answer for each ‘query’, each one line.
Sample Input
5 12
1 5 2 4 3
add 1 4
query 1 4
add 2 5
query 2 5
add 3 5
query 1 5
add 2 4
query 1 4
add 2 5
query 2 5
add 2 2
query 1 5
Sample Output
1
1
2
4
4
6
这应该是到现在做的最难的一道线段树的题目了,(我太菜了);这道题线段树是毫无疑问的,但是这颗树维护什么,怎么维护,是最困难的;看了许多博客,明白了一种写法,就是线段树维护三个变量,一个是a区间的最大值,b区间的最小值,以及ai/bi值的和;但是这三种变量怎么维护呢?首先要明白的是,当一个区间的maxa小于minb时,说明这个区间ai/bi没有值可以加,我们要把懒标记++,直到maxa>=minb并且到达叶子节点时,才说明这个叶子节点(区间)有值可以加,单是maxa>=minb不行;
代码:
#include<bits/stdc++.h>
using namespace std;
int b[100100];
int x,y;
int sum;
struct Node{
int l,r,w,f,maxa,minb;
}tree[400100];
inline void pp(int k){
tree[k].w=tree[k<<1].w+tree[k<<1|1].w;
tree[k].maxa=max(tree[k<<1].maxa,tree[k<<1|1].maxa);
tree[k].minb=min(tree[k<<1].minb,tree[k<<1|1].minb);
}
inline void build(int k,int ll,int rr){
tree[k].l=ll,tree[k].r=rr,tree[k].f=0;
if(ll==rr){
tree[k].maxa=0;
tree[k].minb=b[ll];
tree[k].w=0;
return;
}
int m=(ll+rr)>>1;
build(k<<1,ll,m);
build(k<<1|1,m+1,rr);
pp(k);
}
inline void pd(int k){
if(tree[k].f){
tree[k<<1].f+=tree[k].f;
tree[k<<1|1].f+=tree[k].f;
tree[k<<1].maxa+=tree[k].f;
tree[k<<1|1].maxa+=tree[k].f;
tree[k].f=0;
}
}
inline void add(int k){
if(tree[k].l>=x&&tree[k].r<=y){
tree[k].maxa++;
if(tree[k].maxa<tree[k].minb){
tree[k].f++;
return;
}
if(tree[k].l==tree[k].r&&tree[k].maxa>=tree[k].minb){
tree[k].w++;
tree[k].minb+=b[tree[k].l];
return;
}
}
pd(k);
int m=(tree[k].l+tree[k].r)>>1;
if(x<=m) add(k<<1);
if(y>m) add(k<<1|1);
pp(k);
}
void ask(int k){
if(tree[k].l>=x&&tree[k].r<=y){
sum+=tree[k].w;
return;
}
pd(k);
int m=(tree[k].l+tree[k].r)>>1;
if(x<=m) ask(k<<1);
if(y>m) ask(k<<1|1);
}
int main(){
int n,q;
char c[10];
while(scanf("%d%d",&n,&q)==2){
for(int i=1;i<=n;i++) scanf("%d",&b[i]);
build(1,1,n);
while(q--){
scanf("%s%d%d",c,&x,&y);
if(c[0]=='a'){
add(1);
}
else{
sum=0;
ask(1);
printf("%d\n",sum);
}
}
}
return 0;
}