Time Limit: 2000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Submission(s): 1778 Accepted Submission(s): 547 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 3 Hint 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. |
//题目大意:给出n个苹果的高度,若第k个苹果高度比第K-1个高,则必须将第K个苹果摘掉,输入p,q,表示将第p个苹果的高度换成q,求几个苹果可以摘,每组输入互不干扰;
思路:先求出在到第k个苹果(包括k)前共有fq[i]个苹果可以摘,若p>fq[p-1].maxx(到k前最高的苹果高度),则ans+=fq[k]+1,否则ans+=fq[k];然后从后往前,用栈记录到第p个(不包括第p个)为止,可以摘的苹果的位置,再二分查找到第一个大于q或fq[p-1].maxx的苹果的位置i,ans+=hz[i];
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
const int MAX=1e5+10;
struct FQ
{
int cc;
int maxx;
FQ(){cc=0;}
}fq[MAX];
struct Node
{
int p;
int q;
int index;
friend bool operator<(const Node A,const Node B)
{
if(A.p!=B.p)return A.p<B.p;
else return A.q<B.q;
}
}b[MAX];
int a[MAX];
int hz[MAX];
int ans[MAX];
int main()
{
int t;
while(~scanf("%d",&t))
{
while(t--)
{
memset(ans,0,sizeof(ans));
memset(hz,0,sizeof(hz));
int n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
for(int i=1;i<=m;i++)
{scanf("%d%d",&b[i].p,&b[i].q);b[i].index=i;}
sort(b+1,b+m+1);
fq[0].cc=0;
fq[0].maxx=-1;
for(int i=1;i<=n;i++)
{
if(a[i]>fq[i-1].maxx)
{
fq[i].maxx=a[i];
fq[i].cc=fq[i-1].cc+1;
}else
{
fq[i].maxx=fq[i-1].maxx;
fq[i].cc=fq[i-1].cc;
}
}
int st[MAX];
int top=0;
int now=n;
for(int i=m;i>=1;i--)
{
while(now>b[i].p)
{
while(top!=0&&a[now]>=a[st[top]])top--;
if(top==0)hz[now]=1;
else hz[now]=hz[st[top]]+1;
st[++top]=now;
now--;
}
if(b[i].q>fq[b[i].p-1].maxx)ans[b[i].index]+=fq[b[i].p-1].cc+1;
else {ans[b[i].index]+=fq[b[i].p-1].cc;b[i].q=fq[b[i].p-1].maxx;}
int l=1,r=top,mid,res=0;
while(l<=r)
{
mid=(l+r)/2;
if(b[i].q<a[st[mid]])
{
res=st[mid];
l=mid+1;
}else
r=mid-1;
}
ans[b[i].index]+=hz[res];
}
for(int i=1;i<=m;i++)
printf("%d\n",ans[i]);
}
}
return 0;
}