0
点赞
收藏
分享

微信扫一扫

多校训练5 K King of Range 单调队列

天蓝Sea 2022-03-11 阅读 13
c++学习

King of Range

分析

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;
}
举报

相关推荐

0 条评论