标签:st
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5289
题意:求满足最大值减最小值小于k的区间的数目。
枚举左端点,二分右端点,用st算法求区间最值
代码:
#include <stdio.h>
#include <ctime>
#include <math.h>
#include <limits.h>
#include <complex>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <bitset>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <time.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
using namespace std;
int n, k, p, l, r;
int a[100010];
int s[100010][20];
int maxsum[100010][20], minsum[100010][20];
__int64 ans = 0;
int rmq(int l, int r)
{
int k = log2((double)(r - l + 1));
int MAX = max(maxsum[l][k], maxsum[r - (1 << k) + 1][k]);
int MIN = min(minsum[l][k], minsum[r - (1 << k) + 1][k]);
return MAX - MIN;
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
scanf("%d %d", &n, &k);
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
maxsum[i][0] = minsum[i][0] = a[i];
}
for (int j = 1; (1 << j) <= n; j++)
for (int i = 1; i + (1 << j) - 1 <= n; i++)
{
maxsum[i][j] = max(maxsum[i][j - 1], maxsum[i + (1 << (j - 1))][j - 1]);
minsum[i][j] = min(minsum[i][j - 1], minsum[i + (1 << (j - 1))][j - 1]);
}
ans = 0;
for (int i = 1; i <= n; i++)
{
l = i;
r = n;
while (l + 1 < r)
{
p = (l + r) >> 1;
if (rmq(i, p) < k)
l = p;
else
r = p;
}
if (rmq(i, r) < k)
ans += (__int64)(r - i + 1);
else
ans += (__int64)(l - i + 1);
}
printf("%I64d\n", ans);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:st
原文地址:http://blog.csdn.net/u014427196/article/details/47001889