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
#include <iostream>
#include <cstdio>
#include <algorithm>

typedef long long LL;

using namespace std;

const int MAX = 500000;

int n;
int m;
int a[MAX];
LL high[MAX];
LL prevD[MAX];

int compare (const void * a, const void * b)
{
  return ( *(int*)b - *(int*)a );
}

int main() {

    LL d = 0, b = 0;
    LL sum, currentCut;
    int tmp, i, j;

    scanf("%d %d", &n, &m);

    for(int i=0; i<n; i++) {
        scanf("%d", &tmp);
        a[i] = tmp;
    }

    qsort(a, n, sizeof(int), compare);

    for(i=0; i<m; i++) {
        scanf("%lld %lld", &d, &b);

        sum = 0;

        j = 0;
        while(j < n) {
            currentCut = high[j] + LL(a[j]) * (d - prevD[j]) - b;
            if(currentCut <= 0) {
                // if b is higher than the current grass - grasses are from highest to lowest
                // then sum remains
                break;
            }
            high[j] = b;
            prevD[j] = d;
            sum += currentCut;
            j++;
        };
        // otherwise: if b is higher than the higher grass
        // then sum remains 0

        printf("%lld\n", sum);
    }

    return 0;
}