#include <cstdio> #include <algorithm> #define MAXN 500111 using namespace std; bool czy; int cen, i, k[MAXN], le, m, n, p[MAXN], pr, top; long long a[MAXN], c[MAXN], d[MAXN], dz, prz, sp[MAXN], sum, tam, teraz, tmp, w[MAXN], wys; int main() { scanf("%d%d", &n, &m); for (i = 0; i < n; i++) { scanf("%lld", &a[i]); } sort(a, a+n); sp[0] = a[0]; for (i = 1; i < n; i++) { sp[i] = sp[i-1] + a[i]; } top = 0; p[0] = 0; k[0] = n-1; d[0] = 0; w[0] = 0; c[0] = 0; while (m--) { scanf("%lld%lld", &dz, &wys); czy = false; sum = 0; if (wys >= a[n-1]*(dz-d[top])+w[top]) { printf("0\n"); continue; } if (top == 0) { czy = true; } while (!czy) { tam = a[k[top-1]]*(dz-d[top-1])+w[top-1]; if (wys >= tam) { czy = true; } else { sum += c[top]; top--; } } if (a[p[top]]*(dz-d[top])+w[top] >= wys) { cen = p[top]; } else if (a[k[top]]*(dz-d[top])+w[top] <= wys) { cen = k[top]; } else { le = p[top]; pr = k[top]; while (le+1<pr) { cen = (le+pr)/2; tmp = a[cen]*(dz-d[top])+w[top]; if (tmp < wys) { le = cen; } else { pr = cen; } } cen = pr; } if (cen == 0) { prz = sp[n-1]; } else { prz = sp[n-1] - sp[cen-1]; } teraz = (n-cen)*(w[top]-wys) + (dz-d[top]) * prz; teraz -= sum; printf("%lld\n", teraz); if (cen > p[top]) { k[top] = cen-1; top++; } p[top] = cen; k[top] = n-1; d[top] = dz; w[top] = wys; c[top] = teraz; } 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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | #include <cstdio> #include <algorithm> #define MAXN 500111 using namespace std; bool czy; int cen, i, k[MAXN], le, m, n, p[MAXN], pr, top; long long a[MAXN], c[MAXN], d[MAXN], dz, prz, sp[MAXN], sum, tam, teraz, tmp, w[MAXN], wys; int main() { scanf("%d%d", &n, &m); for (i = 0; i < n; i++) { scanf("%lld", &a[i]); } sort(a, a+n); sp[0] = a[0]; for (i = 1; i < n; i++) { sp[i] = sp[i-1] + a[i]; } top = 0; p[0] = 0; k[0] = n-1; d[0] = 0; w[0] = 0; c[0] = 0; while (m--) { scanf("%lld%lld", &dz, &wys); czy = false; sum = 0; if (wys >= a[n-1]*(dz-d[top])+w[top]) { printf("0\n"); continue; } if (top == 0) { czy = true; } while (!czy) { tam = a[k[top-1]]*(dz-d[top-1])+w[top-1]; if (wys >= tam) { czy = true; } else { sum += c[top]; top--; } } if (a[p[top]]*(dz-d[top])+w[top] >= wys) { cen = p[top]; } else if (a[k[top]]*(dz-d[top])+w[top] <= wys) { cen = k[top]; } else { le = p[top]; pr = k[top]; while (le+1<pr) { cen = (le+pr)/2; tmp = a[cen]*(dz-d[top])+w[top]; if (tmp < wys) { le = cen; } else { pr = cen; } } cen = pr; } if (cen == 0) { prz = sp[n-1]; } else { prz = sp[n-1] - sp[cen-1]; } teraz = (n-cen)*(w[top]-wys) + (dz-d[top]) * prz; teraz -= sum; printf("%lld\n", teraz); if (cen > p[top]) { k[top] = cen-1; top++; } p[top] = cen; k[top] = n-1; d[top] = dz; w[top] = wys; c[top] = teraz; } return 0; } |