HDU-5289(单调队列)
来源:互联网 发布:中国报学史读后感知乎 编辑:程序博客网 时间:2024/06/05 18:41
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.
24 23 1 2 410 50 3 4 5 2 1 6 7 8 9
528
First Sample, the satisfied groups include:[1,1]、[2,2]、[3,3]、[4,4] 、[2,3]
题目大意:给你一个序列,1~n。问你有几个连续子序列满足其中最大值和最小值的差小于k。
分析:又是一道单调队列的题,我们设立两个指针i、j,从头开始往右移动,力求在O(n)的复杂度扫描一遍解决问题。单调队列的作用是什么呢,它是以很小的时间代价动态更新当前序列中的最大最小值。(此处如果有不懂请自行学习单调队列,此处只需要知道它动态更新最大最小值即可)。[j,i-1]表示当前关注的序列,我们将i指针一直向前,去更新最大最小值,直到[j,i]的最值之差>=k,说明此时的[j,i-1]是极限了。那么以 j 为起点的序列就只能从[j,i-1]选一个终点,有i-j种选法。然后j向前移动一位,重复以上过程,一直到 i 更新完整个序列。
#include<math.h>#include<stdio.h>#include<iostream>#include<deque>#include<string.h>using namespace std;int num[100005];int main(){int t;cin >> t;deque<int>high;deque<int>low;int n, k;long long int ans;while (t--){ans = 0;high.clear();low.clear();cin >> n >> k;for (int i = 1; i <= n; i++){scanf("%d", &num[i]);}int i, j;for (j = i = 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;}
阅读全文
0 0
- HDU-5289(单调队列)
- hdu 5289 单调队列
- hdu 5289 单调队列
- HDU 5289 单调队列,multiset
- HDU 5289 Assignment(单调队列)
- hdu 4193(单调队列)
- hdu 3415(单调队列)
- hdu 3410(单调队列)
- HDU-4193 (单调队列)
- hdu 3530(单调队列)
- hdu 5289 Assignment(RMQ,单调队列,multiset)
- Hdu-5289 Assignment (二分+RMQ || 单调队列)
- hdu Parade(单调队列优化 dp)
- HDU 3530 Subsequence(单调队列)
- hdu 3401 Trade (单调队列优化)
- HDU 3530 Subsequence(单调队列)
- HDU 3530Subsequence(单调队列维护)
- hdu 5261 蜀道难 (单调队列)@
- Python——解析命令行参数docopt模块
- 正交向量与正交子空间
- Python中MD5编码
- 聚类算法--K值估计及效果评估
- SGI版的空间配置器
- HDU-5289(单调队列)
- java 锁的介绍
- 5. Longest Palindromic Substring
- java 内存区域介绍
- 1.科学计算与三维可视化的概念
- ssh总结
- MyBatis 框架的搭建和配置
- 约瑟夫问题,过程推理,递归
- Python入门系列——第5篇