题目链接:hdu 6319 Problem A. Ascending Rating
Sample Input
1
10 6 10 5 5 5 5
3 2 2 1 5 7 6 8 2 9
Sample Output
46 11
题意:给定一个序列a[n],对于每个长度为m的连续子区间,求出区间a的最大值从左往右扫描时a的最大值的变化次数count,以及区间最大值,并且根据公式求得A,B输出
思路:一开始我的思路是sort了一遍,但是看数据发现NlogN是过不了的,看了题解,发现需要用到双向队列,这是个滑动窗口的问题,滑动窗口具体可以看这篇博客(笔试题)滑动窗口的最大值。具体实现是,手动用队列维护一个严格递减的序列,(注意队列存的不是序列a的值,而是下标,这是为了后面区间移动判断方便),从后往前处理区间,区间移动的时候,若队列的头,即最大值,不在当前区间范围内,则弹出,新增的区间元素与队尾比较,若新增元素小于队尾所指的元素,则压入队尾,否则弹出队尾元素,直至队列为空,或新增元素小于当前队尾所指元素,再压入。每次区间移动,更新队列之后,队列中的元素即最大值的变化次数,队头所指元素,即最大值。至于复杂度,队列中的每一个元素最多入队出队一次,是O(N)的。要注意的是,0这个元素需要特判,因为count初始值是0,当扫描到大于0的元素时,才能count++
#include<cstring>
#include<cstdio>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
ll a[10000007];
ll qu[20000007];
int main(){
int t;
scanf("%d",&t);
while(t--){
ll n,m,k,p,q,r,mod,pre,now;
scanf("%lld%lld%lld%lld%lld%lld%lld",&n,&m,&k,&p,&q,&r,&mod);
ll ansa=0;
ll ansb=0;
for(ll i=1;i<=k;i++){
scanf("%lld",&a[i]);
}
for(ll i=k+1;i<=n;i++){
a[i]=(p*a[i-1]+q*i+r)%mod;
}
int head=1,end=1;
int tot=0;
for(ll i=n;i>=n-m+1;i--){//处理第一个区间
if(!tot){
if(a[i]==0)continue;//0不压入队列
qu[end]=i;
end++;
tot++;
}
else{
while(tot&&(a[i]>=a[qu[end-1]])){
end--;
tot--;
}
qu[end]=i;
end++;
tot++;
}
}
for(ll i=n;i>=m;i--){
ansa+=((ll)a[qu[head]]^(ll)(i-m+1));
ansb+=((ll)(tot)^(ll)(i-m+1));
if((i-1)<m)continue;
if(i<=qu[head]){//判断队列头是否在下一个区间范围内,这里一开始写了==,需要仔细思考
head++;
tot--;
}
while(tot&&(a[i-m]>=a[qu[end-1]])){
end--;
tot--;
}
if((a[i-m]==0))continue;//同样0不压入
qu[end]=i-m;
end++;
tot++;
}
printf("%lld %lld\n",ansa,ansb);
}
return 0;
}
/*
1
10 6 10 5 5 5 5
3 2 2 1 5 7 6 8 2 9
1
10 6 10 5 5 5 5
0 0 0 0 0 0 0 0 0 0
1
6 3 6 5 5 5 5
0 0 0 1 2 3
1
6 3 6 5 5 5 5
1 2 3 0 0 0
1
6 3 6 5 5 5 5
1 0 2 3 0 0
*/