1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| #include <cstdio> #include <iostream> #include <algorithm> #define inf 2147483647 #define maxN 200010 using namespace std; struct Query{ long long x, y, pos; } a[maxN]; long long sum[maxN]; long long queue[maxN][2], h[maxN]; long long Ans[maxN], L[maxN], R[maxN]; bool cmp (Query A, Query B) { return A.x < B.x; } int main () { long long n = 0, q = 0; scanf("%lld %lld", &n, &q); for(long long i = 1;i <= n; i++) { scanf("%lld", &h[i]); sum[i] = sum[i - 1] + h[i]; } for(long long i = 1;i <= q; i++) { a[i].pos = i; scanf("%lld %lld", &a[i].x, &a[i].y); } sort(a + 1, a + q + 1, cmp); long long len = 0, now = 1; queue[0][0] = inf, queue[0][1] = 0; for(long long i = 1;i <= n; i++) { while(a[now].x == i && now <= q) { long long y = a[now].y; long long l = 0, r = len; while(l < r) { long long mid = (l + r + 1) >> 1; if(queue[mid][0] >= y) { l = mid; } else { r = mid - 1; } } L[a[now].pos] = queue[l][1] + 1; now++; } while(queue[len][0] < h[i]) { len--; } len++; queue[len][0] = h[i], queue[len][1] = i; } len = 0, now = q; queue[0][0] = inf, queue[0][1] = n + 1; for(long long i = n;i >= 1; i--) { while(a[now].x == i && now <= q) { long long y = a[now].y; long long l = 0, r = len; while(l < r) { long long mid = (l + r + 1) >> 1; if(queue[mid][0] >= y) { l = mid; } else { r = mid - 1; } } R[a[now].pos] = queue[l][1] - 1; Ans[a[now].pos] = y * (R[a[now].pos] - L[a[now].pos] + 1) - (sum[R[a[now].pos]] - sum[L[a[now].pos] - 1]); now--; } while(queue[len][0] < h[i]) { len--; } len++; queue[len][0] = h[i], queue[len][1] = i; } for(long long i = 1;i <= q; i++) { printf("%lld\n", Ans[i]); } return 0; }
|