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:
1. add l r: add one for al,al+1...aral,al+1...ar
2. query l r: query ∑ri=l⌊ai/bi⌋∑i=lr⌊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≤1000001≤n,q≤100000, 1≤l≤r≤n1≤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[L,R]+1 求A[i]/B[i] 向下取整
初始的时候A[i]为0,B[i]给定,当出现一个“1”时,应该是Ai=Bi的时候,所以对A数组的加1可以对应的转化为对B数组的减1,当B数组为0时,贡献一个1,查询的时候查询值就行了。
#include <bits/stdc++.h>
#define maxn 100066
using namespace std;
typedef long long ll;
struct Tree{
ll sum,valb,minn,add;
}tr[maxn<<2];
int n,q;
int a[maxn],b[maxn];
void push_up(int rt){//维护区间bi的最小值以及答案
tr[rt].minn=min(tr[rt<<1].minn,tr[rt<<1|1].minn);
tr[rt].sum=tr[rt<<1].sum+tr[rt<<1|1].sum;
}
void push_down(int rt){//lazy操作
if(tr[rt].add){
tr[rt<<1].add+=tr[rt].add;
tr[rt<<1|1].add+=tr[rt].add;
tr[rt<<1].minn-=tr[rt].add;
tr[rt<<1|1].minn-=tr[rt].add;
tr[rt].add=0;
}
}
void build(int l,int r,int rt){//建树
tr[rt].add=tr[rt].sum=0;
if(l==r){
tr[rt].minn=tr[rt].valb=b[l];//叶子节点
tr[rt].sum=0;
return;
}
int mid=(l+r)>>1;
build(l,mid,rt<<1);
build(mid+1,r,rt<<1|1);//两边建树
push_up(rt);
}
void update(int L,int R,int l,int r,int rt){//区间更新,l,r是抽象节点区间
//如果询问区间[L,R]能被覆盖且[L,R]的最小值大于0,则进行-1操作
if(L<=l&&R>=r&&tr[rt].minn>1){
tr[rt].add++;//最小值减一、
tr[rt].minn--;//增加add标记,表示本区间维护的值正确,子区间不一定
return;
}
//否则不断遍历到叶子结点并判断当前bi的值是否为0
if(l==r&&tr[rt].minn==1){
tr[rt].sum++;//此时和加一
tr[rt].minn=tr[rt].valb;//最小值更新为叶子节点值
tr[rt].add=0;//清除标记
return;
}
int mid=(l+r)>>1;
push_down(rt);
if(L<=mid) update(L,R,l,mid,rt<<1);//
if(R>mid) update(L,R,mid+1,r,rt<<1|1);
push_up(rt);
}
ll query(int L,int R,int l,int r,int rt){//区间求和
if(L<=l&&R>=r){
return tr[rt].sum;
}
int mid=(l+r)>>1;
push_down(rt);//及时下推标记
ll ans=0;
if(L<=mid) ans+=query(L,R,l,mid,rt<<1);
if(R>mid) ans+=query(L,R,mid+1,r,rt<<1|1);//
return ans;
}
int main()
{
while(~scanf("%d%d",&n,&q)){
for(int i=1;i<=n;i++){
scanf("%d",&b[i]);//利用b数组建树
}
build(1,n,1);
while(q--){
string str;
cin>>str;
int l,r;
scanf("%d%d",&l,&r);
if(str[0]=='a'){
update(l,r,1,n,1);
}
else{
ll res=query(l,r,1,n,1);
printf("%lld\n",res);
}
}
}
return 0;
}