Description
Input
Output
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]
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<deque>
using namespace std;
const int MAXN = 1e5 + 10;
int numbers[MAXN];
deque<int> high;
deque<int> low;
int main()
{
int kase;
cin >> kase;
int n, k;
while(kase--)
{
cin >> n >> k;
for(int i = 1; i <= n; i++)
{
scanf( "%d", &numbers[i] );
}
high.clear();
low.clear();
int i, j; //i is pre pointer
long long ans = 0;
for(i = j = 1; i <= n; i++)
{
while(!high.empty() && high.back() < numbers[i]) high.pop_back();
high.push_back( numbers[i] );
while(!low.empty() && low.back() > numbers[i]) low.pop_back();
low.push_back( numbers[i] );
while(!high.empty() && !low.empty() && high.front() - low.front() >= k)
{
ans += i - j;
if(high.front() == numbers[j]) high.pop_front();
if(low.front() == numbers[j]) low.pop_front();
//如果j已经前移出了最小值所在位置,则弹出
j++;
}
}
while(j <= n)
//不要忘记
{
ans += i - j;
j++;
}
cout << ans << endl;
}
return 0;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/maxichu/article/details/47612497