2018/7/16 Assignment 训练日记1

单调队列   滑动窗口问题

可以学会双向队列deque的使用

deque常用的成员函数

      deque<int>deq;

  1. deq[ ]:用来访问双向队列中单个的元素。
  2. deq.front():返回第一个元素的引用。
  3. deq.back():返回最后一个元素的引用。
  4. deq.push_front(x):把元素x插入到双向队列的头部。
  5. deq.pop_front():弹出双向队列的第一个元素。
  6. deq.push_back(x):把元素x插入到双向队列的尾部。
  7. deq.pop_back():弹出双向队列的最后一个元素。

Assignment

Problem Description

Tom owns a company and he is the boss. There are n staffs which are numbered from 1 to n in this company, and every staff has a ability. Now, Tom is going to assign a special task to some staffs who were in the same group. In a group, the difference of the ability of any two staff is less than k, and their numbers are continuous. Tom want to know the number of groups like this.

 

 

Input

In the first line a number T indicates the number of test cases. Then for each case the first line contain 2 numbers n, k (1<=n<=100000, 0<k<=10^9),indicate the company has n persons, k means the maximum difference between abilities of staff in a group is less than k. The second line contains n integers:a[1],a[2],…,a[n](0<=a[i]<=10^9),indicate the i-th staff’s ability.

Output

For each test,output the number of groups.

Sample Input

2 4 2 3 1 2 4 10 5 0 3 4 5 2 1 6 7 8 9

Sample Output

5 28

Hint

First Sample, the satisfied groups include:[1,1]、[2,2]、[3,3]、[4,4] 、[2,3]

 

题目大意:给你一个序列1-n,

问你有几个连续子序列满足其中最大值和最小值的差小于k。

分析:设立两个指针i,j,从头开始往右移动,[j,i-1]表示当前关注的序列,我们将i指针一直向前,去更新最大最小值,直到[j,i]的最值之差>=k,说明此时的[j,i-1]是极限了。那么以 j 为起点的序列就只能从[j,i-1]选一个终点,有i-j种选法。然后j向前移动一位,重复以上过程,一直到 i 更新完整个序列。

#include<bits/stdc++.h>
using namespace std;
const int MAXN=100010;
int num[MAXN];
deque<int>high;
deque<int>low;
int main()
{
int t;
cin>>t;
int n,k;
while(t--)
{
int i,j;
long long ans=0;
cin>>n>>k;
for(int i=1;i<=n;i++)
                scanf("%d",&num[i]);
high.clear();
low.clear();
for(i=j=1;i<=n;i++)
{
while(!high.empty()&&high.back()<num[i])
                        high.pop_back();
high.push_back(num[i]);
while(!low.empty()&&low.back()>num[i])
low.pop_back();
low.push_back(num[i]);
while(!high.empty()&&!low.empty()&&high.front()-low.front()>=k)
{
ans+=i-j;
if(high.front()==num[j])
high.pop_front();
if(low.front()==num[j])
low.pop_front();
j++;
}
}
while(j<=n)
{
ans+=i-j;
j++;
}
cout<<ans<<endl;
}
return 0;
}

这个题其实还有其他的解法,比如用线段树、RMQ+二分都有相关的解法,但是感觉双向队列比较方便也比较好理解

所以最后还是采用了这种做法。

相关类型的题目主要也是涉及到单调队列或者线段树这一方面的题目。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值