标签:double 最大 st表 const cas 长度 iostream 代码 math
#include <algorithm>
#include <cmath>
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::max;
using std::min;
template <typename T>
inline const T &max(const T &a, const T &b, const T &c)
{
return max(a, max(b, c));
}
const double LOG2 = std::log(2);
int a[200010];
int maxval[200010][50];
int minval[200010][50];
int ans[200010][50];
int rans[200010][50];
int n, m;
inline void stInit()
{
for (int i = 1; i <= n; ++i)
minval[i][0] = maxval[i][0] = a[i];
for (int j = 1; 1 << j <= n; ++j)
for (int i = 1; i + (1 << j) - 1 <= n; ++i)
{
minval[i][j] = min(minval[i][j - 1], minval[i + (1 << (j - 1))][j - 1]);
maxval[i][j] = max(maxval[i][j - 1], maxval[i + (1 << (j - 1))][j - 1]);
ans[i][j] = max(ans[i][j - 1], ans[i + (1 << (j - 1))][j - 1],
maxval[i + (1 << (j - 1))][j - 1] - minval[i][j - 1]);
rans[i][j] = max(rans[i][j - 1], rans[i + (1 << (j - 1))][j - 1],
maxval[i][j - 1] - minval[i + (1 << (j - 1))][j - 1]);
}
}
inline int queryMax(int l, int r)
{
int k = static_cast<int>(std::log(r - l + 1) / LOG2);
return max(maxval[l][k], maxval[r - (1 << k) + 1][k]);
}
inline int queryMin(int l, int r)
{
int k = static_cast<int>(std::log(r - l + 1) / LOG2);
return min(minval[l][k], minval[r - (1 << k) + 1][k]);
}
inline int queryAns(int l, int r)
{
int k = static_cast<int>(std::log(r - l + 1) / LOG2);
if (l + (1 << k) > r)
return max(ans[l][k], ans[r - (1 << k) + 1][k]);
else
return max(ans[l][k], ans[r - (1 << k) + 1][k],
queryMax(l + (1 << k), r) - queryMin(l, r - (1 << k)));
}
inline int queryRans(int l, int r)
{
int k = static_cast<int>(std::log(r - l + 1) / LOG2);
if (l + (1 << k) > r)
return max(rans[l][k], rans[r - (1 << k) + 1][k]);
else
return max(rans[l][k], rans[r - (1 << k) + 1][k],
queryMax(l, r - (1 << k)) - queryMin(l + (1 << k), r));
}
int main()
{
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> a[i];
stInit();
cin >> m;
while (m--)
{
int l, r;
cin >> l >> r;
if (l < r)
cout << queryAns(l, r) << endl;
else if (l > r)
cout << queryRans(r, l) << endl;
else
cout << 0 << endl;
}
return 0;
}
标签:double 最大 st表 const cas 长度 iostream 代码 math
原文地址:https://www.cnblogs.com/Xchu/p/11619268.html