题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5289
题意:求满足区间内最大值和最小值差为k的区间个数。
预处理出区间的最值,枚举左端点,根据最值的单调性二分枚举右端点,使得找到最右侧max-min<k,区间数为[i,...hi]的个数,即hi-i+1个。
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 typedef long long LL; 5 typedef pair<int, int> pii; 6 const int maxn = 200200; 7 int dp[maxn][20][2]; 8 int a[maxn]; 9 int n, k; 10 11 void st(int* a, int* b, int n) { 12 for(int i = 1; i <= n; i++) dp[i][0][0] = b[i], dp[i][0][1] = a[i]; 13 for(int j = 1; (1 << j) - 1 <= n; j++) { 14 for(int i = 1; i + (1 << j) - 1 <= n; i++) { 15 dp[i][j][0] = min(dp[i][j-1][0], dp[i+(1<<(j-1))][j-1][0]); 16 dp[i][j][1] = max(dp[i][j-1][1], dp[i+(1<<(j-1))][j-1][1]); 17 } 18 } 19 } 20 21 pii query(int l, int r) { 22 int k = int(log(r-l+1) / log(2.0)); 23 return pii(min(dp[l][k][0], dp[r-(1<<k)+1][k][0]), max(dp[l][k][1], dp[r-(1<<k)+1][k][1])); 24 } 25 26 int main() { 27 // freopen("in", "r", stdin); 28 int T; 29 scanf("%d", &T); 30 while(T--) { 31 scanf("%d%d",&n,&k); 32 for(int i = 1; i <= n; i++) scanf("%d", &a[i]); 33 st(a, a, n); 34 LL ret = 0; 35 for(int i = 1; i <= n; i++) { 36 int lo = i, hi = n; 37 while(lo <= hi) { 38 int mid = (lo + hi) >> 1; 39 pii q = query(i, mid); 40 int minn = q.first, maxx = q.second; 41 if(maxx - minn < k) lo = mid + 1; 42 else hi = mid - 1; 43 } 44 ret += (hi - i + 1); 45 } 46 printf("%I64d ", ret); 47 } 48 return 0; 49 }