#include <cstdio> #include <set> #include <algorithm> typedef long long i64; const int N = 200000 + 10; int n, m, right[N]; i64 t[N], sum[N], ans[N]; std::set<std::pair<i64, int>> heap; inline i64 calc(int l) { int r = right[l]; return (t[r + 1] - t[l]) / (r + 1 - l); } i64 k, b; void del(int l) { int r = right[l]; k -= (r - l + 1LL) * (r - l) / 2; b -= (sum[r] - sum[l]) - t[l] * (r - l); } void ins(int l) { int r = right[l]; k += (r - l + 1LL) * (r - l) / 2; b += (sum[r] - sum[l]) - t[l] * (r - l); } void meld(int l) { int p = right[l] + 1; heap.erase({calc(l), l}); heap.erase({calc(p), p}); del(l); del(p); right[l] = right[p]; ins(l); heap.emplace(calc(l), l); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) scanf("%lld", &t[i]); t[n + 1] = 2000000000000LL; for (int i = 1; i <= n + 1; ++i) sum[i] = sum[i - 1] + t[i]; for (int i = 0; i <= n + 1; ++i) right[i] = i; for (int i = 0; i <= n; ++i) heap.emplace(calc(i), i); static std::pair<int, int> d[N]; for (int i = 1; i <= m; ++i) scanf("%d", &d[i].first), d[i].second = i; std::sort(d + 1, d + m + 1); for (int i = 1; i <= m; ++i) { int x = d[i].first; while (!heap.empty() && x > heap.begin()->first) meld(heap.begin()->second); ans[d[i].second] = k * x - b; } for (int i = 1; i <= m; ++i) printf("%lld\n", ans[i]); return 0; }
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 | #include <cstdio> #include <set> #include <algorithm> typedef long long i64; const int N = 200000 + 10; int n, m, right[N]; i64 t[N], sum[N], ans[N]; std::set<std::pair<i64, int>> heap; inline i64 calc(int l) { int r = right[l]; return (t[r + 1] - t[l]) / (r + 1 - l); } i64 k, b; void del(int l) { int r = right[l]; k -= (r - l + 1LL) * (r - l) / 2; b -= (sum[r] - sum[l]) - t[l] * (r - l); } void ins(int l) { int r = right[l]; k += (r - l + 1LL) * (r - l) / 2; b += (sum[r] - sum[l]) - t[l] * (r - l); } void meld(int l) { int p = right[l] + 1; heap.erase({calc(l), l}); heap.erase({calc(p), p}); del(l); del(p); right[l] = right[p]; ins(l); heap.emplace(calc(l), l); } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) scanf("%lld", &t[i]); t[n + 1] = 2000000000000LL; for (int i = 1; i <= n + 1; ++i) sum[i] = sum[i - 1] + t[i]; for (int i = 0; i <= n + 1; ++i) right[i] = i; for (int i = 0; i <= n; ++i) heap.emplace(calc(i), i); static std::pair<int, int> d[N]; for (int i = 1; i <= m; ++i) scanf("%d", &d[i].first), d[i].second = i; std::sort(d + 1, d + m + 1); for (int i = 1; i <= m; ++i) { int x = d[i].first; while (!heap.empty() && x > heap.begin()->first) meld(heap.begin()->second); ans[d[i].second] = k * x - b; } for (int i = 1; i <= m; ++i) printf("%lld\n", ans[i]); return 0; } |