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
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector < long long > tempo, pref;
vector < pair < int, pair < long long, long long > > > zboze;
int n,m;
int main(){
    scanf("%d%d",&n,&m);
    for (int i = 0; i < n; i++){
        int a;
        scanf("%d",&a);
        tempo.push_back(a);
    }
    sort(tempo.begin(), tempo.end());
    tempo.insert(tempo.begin(), 0);
    pref.push_back(0);
    for (int i = 1; i <= n; i++){
        pref.push_back(tempo[i] + pref[i-1]);
    }
    zboze.push_back(make_pair(0, make_pair(0,0)));
    for (int i = 0; i < m; i++){
        long long res = 0;
        long long d,b;
        scanf("%lld%lld",&d,&b);
        int e = 0, f = zboze.size()-1, l = 0, w = -1, p;
        while (e <= f){
            int mid = (e+f)/2;
            if (tempo[ zboze[mid].first ] * (d - zboze[mid].second.first) + zboze[mid].second.second <= b){
                l = mid;
                e = mid + 1;
            }
            else {
                f = mid - 1;
            }
        }
        e = zboze[ l ].first;
        if (l < zboze.size()-1){
            f = zboze[ l+1 ].first - 1;
        }
        else {
            f = n;
        }
        p = f;
        while (e <= f){
            int mid = (e+f)/2;
            if (l < zboze.size()-1);
            if (tempo[ mid ] * (d - zboze[l].second.first) + zboze[l].second.second <= b){
                w = mid;
                e = mid + 1;
            }
            else {
                f = mid - 1;
            }
        }
        int first_w = w;
        res += (pref[p] - pref[w]) * (d - zboze[l].second.first) + zboze[l].second.second * (p - w) - b * (p - w);
        for (int j = l+1; j < zboze.size(); j++){
            if (j < zboze.size()-1){
                p = zboze[j+1].first - 1;
            }
            else {
                p = n;
            }
            w = zboze[j].first - 1;
            res += (pref[p] - pref[w]) * (d - zboze[j].second.first) + zboze[j].second.second * (p - w) - b * (p - w);
        }
        int zboze_size = zboze.size();
        for (int j = l+1; j < zboze_size; j++){
            zboze.pop_back();
        }
        if (first_w < n){
            zboze.push_back(make_pair(first_w+1, make_pair(d,b)));
        }
        printf("%lld\n", res);
    }
}