Taotao Picks ApplesTime Limit: 2000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 3140 Accepted Submission(s): 976 Problem Description There is an apple tree in front of Taotao's house. When autumn comes, n apples on the tree ripen, and Taotao will go to pick these apples. Input The first line of input is a single line of integer T (1≤T≤10) , the number of test cases. Output For each query, display the answer in a single line. Sample Input 1 5 3 1 2 3 4 4 1 5 5 5 2 3 Sample Output 1 5 3Hint For the first query, the heights of the apples were 5, 2, 3, 4, 4, so Taotao would only pick the first apple. For the second query, the heights of the apples were 1, 2, 3, 4, 5, so Taotao would pick all these five apples. For the third query, the heights of the apples were 1, 3, 3, 4, 4, so Taotao would pick the first, the second and the fourth apples. |
#include<bits/stdc++.h>
using namespace std;
int n,m,t,f[1000005],g[1000005],a[1000005];
int query(int l,int r,int res,int v)
{
if(l==r) return f[res]>v;//如果到了根节点 判断是否大于v 大于则返回1不然就返回0
if(f[res]<=v) return 0;//这个区间最大的一个数都小于v那么这个区间就没有贡献
int mid=(l+r)/2;
if(f[res*2]<=v) return query(mid+1,r,res*2+1,v);//如果左边的结果小于v 那么只有右边才可以 左边的都不行
else return g[res]-g[res*2]+query(l,mid,res*2,v);//不然的话就是加上右边的值 再递归找到左儿子的值
}
void build(int l,int r,int res)
{
if(l==r)
{
f[res]=a[l];
g[res]=1;
return;
}
int mid=(r+l)/2;
build(l,mid,res*2);
build(mid+1,r,res*2+1);
f[res]=max(f[res*2],f[res*2+1]);
g[res]=g[res*2]+query(mid+1,r,res*2+1,f[res*2]);//能选的苹果数等于左边的苹果数加上右边符合条件的苹果数
}
void update(int l,int r,int res,int x,int y)
{
if(l==r)
{
f[res]=y;
g[res]=1;
return;
}
int mid=(l+r)/2;
if(x<=mid) update(l,mid,res*2,x,y);
else update(mid+1,r,res*2+1,x,y);
f[res]=max(f[res*2],f[res*2+1]);
g[res]=g[res*2]+query(mid+1,r,res*2+1,f[res*2]);
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,n,1);//建树
while(m--)
{
int x,y;
scanf("%d%d",&x,&y);
int temp=a[x];
update(1,n,1,x,y);
printf("%d\n",g[1]);
update(1,n,1,x,temp);//把原先的操作改回来
}
}
return 0;
}