51nod_1275 连续子段的差异(单调队列)

连续子段的差异

Problem Description

给出一个包括N个元素的整数数组A,包括A本身在内,共有 (N+1)*N / 2个非空子段。例如:1 3 2的子段为{1} {3} {2} {1 3} {3 2} {1 3 2}。在这些子段中,如果最大值同最小值的差异不超过K,则认为这是一个合格的子段。给出数组A和K,求有多少符合条件的子段。例如:3 5 7 6 3,K = 2,符合条件的子段包括:{3} {5} {7} {6} {3} {3 5} {5 7} {7 6} {5 7 6},共9个。

Input

第1行:2个数N, K(1 <= N <= 50000, 0 <= K <= 10^9)
第2 - N + 1行:每行1个数,对应数组的元素Ai(0 <= A[i] <= 10^9)

Output

输出符合条件的子段数量。

Sample Input

5 2
3
5
7
6
2

Sample Output

9

题解:

计算满足条件的子段数量,可以固定左端点,求右端点最多能到达的位置。可以利用了两个单调队列,分别维护最大值和最小值,若加入第j个元素满足max-min<=k,则将第j个元素放入单调队列中,并继续考虑下一个元素;否则 a n s + = j − i ans += j-i ans+=ji

#include<stdio.h>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<ctype.h>
#include<cstring>
#include<map>
#include<vector>
#include<queue>
#define dbg(x) cout<<#x<<" = "<<x<<endl;
#define INF 0x3f3f3f3f
#define LLINF 0x3f3f3f3f3f3f3f3f
#define eps 1e-6
 
using namespace std;
typedef long long LL;   
typedef pair<int, int> P;
const int maxn = 50010;
const int mod = 1000000007;
struct node{
    int w, pos;
    node(){}
    node(int a, int b):pos(a),w(b){}
};
int a[maxn];
deque<node> deq1, deq2;

int main()
{
    int n, i, j, k;
    LL ans = 0;
    scanf("%d %d", &n, &k);
    for(i=0;i<n;i++)
        scanf("%d", &a[i]);
    j = 0;
    for(i=0;i<n;i++)
    {
        while(deq1.size() && deq1.front().pos < i)
            deq1.pop_front();
        while(deq2.size() && deq2.front().pos < i)
            deq2.pop_front();
        while(j<n)
        {
            if(deq1.size()!=0 && max(a[j],deq1.front().w)-min(a[j], deq2.front().w)>k)
                break;
            while(deq1.size() && a[j] >= deq1.back().w)
                deq1.pop_back();
            deq1.push_back(node(j, a[j]));
            while(deq2.size() && a[j] <= deq2.back().w)
                deq2.pop_back();
            deq2.push_back(node(j, a[j]));
            j++;
        }
        ans += j-i;
    }
    printf("%lld\n", ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值