分析
题意:在有n个数的序列里,有m组询问,每次询问给出一个常数k,求有多少(l, r)区间满足极差大于k,输出这样的区间个数。
思路:用两个单调队列分别维护最大值和最小值,每次固定左边界,只需要寻找满足条件的最小的右边界,后面的都满足,加上差值即可。(n - r +1)
accode:
双指针+单调队列
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 7;
int n, m, k;
int h1, t1, h2, t2;
int a[maxn];
ll ans;
struct node{
int x, p;
node(){}
node(int xx, int pp){x = xx; p = pp;}
}q[maxn], p[maxn];
int main()
{
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
while(m--)
{
ans = 0;
scanf("%d", &k);
h1 = 1, t1 = 1, h2 = 1, t2 = 1;
q[1] = node(a[1], 1);
p[1] = node(a[1], 1);
for(int l = 1, r = 1; r <= n; r++)
{
while(h1 <= t1 && q[t1].x <= a[r])
t1--;
q[++t1] = node(a[r], r);
while(h2 <= t2 && p[t2].x >= a[r])
t2--;
p[++t2] = node(a[r], r);
while(q[h1].x - p[h2].x > k)
{
ans += 1ll * (n- r + 1);
l++;
if(l > q[h1].p) h1++;
if(l > p[h2].p) h2++;
}
}
printf("%lld\n", ans);
}
return 0;
}
双端队列
做法(好像差不多):
accode:
#include <stdio.h>
#include <iostream>
#include <queue>
#include <string.h>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
#define ios std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
const int maxn = 1e5 + 7;
typedef long long ll;
int a[maxn];
int main()
{
ios;
int n, m, k;//n个数,m次查询,极差为k
scanf("%d %d", &n, &m);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
while(m--)
{
scanf("%d", &k);
deque<int> qmin, qmax;//构造两个双端队列,一个为递减序列维护最大值,一个为递增序列维护最小值
ll ans = 0;
for(int l = 1, r = 1; r <= n; r++)
{
while(qmax.size() && a[qmax.back()] < a[r])//删尾
qmax.pop_back();
qmax.push_back(r);
while(qmin.size() && a[qmin.back()] > a[r])
qmin.pop_back();
qmin.push_back(r);
while(a[qmax.front()] - a[qmin.front()] > k)//如果它俩的差值大于等于k,即l到r区间都成立
{
ans += 1ll * (n - r + 1);
l++;//往右更新左区间
if(qmax.front() < l)//去头
qmax.pop_front();
if(qmin.front() < l)
qmin.pop_front();
}
}
printf("%lld\n", ans);
}
return 0;
}