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
#include <iostream>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <set>
using namespace std;
int gat[500003];
int n, m, i, j, pocz, kon, p, k, k2;
unsigned long long d2, b, d1 = 0, il, wyn, pre[500003], h[500003],wsp[500003],w = 0;
vector<int> zbior;

int wyszukaj_bin(int p, int k, unsigned long long b){
	while(p < k) {
		int s = (p + k + 1)/2;
		//cout << "s=" <<s << endl;
		if( (w - wsp[pocz]) * gat[s] + h[pocz] > b )
			k = s - 1;
		else p = s;	
	} 
	return p + 1;
}
int main()
{
ios_base::sync_with_stdio(0);
cin >> n >> m;
for(i = 1; i <= n; ++i) cin >> gat[i];
sort(gat, gat + n + 1);
for(i = 1; i <= n; ++i) pre[i] = pre[i-1] + gat[i];
//for(i = 1; i <= n; ++i) cout << pre[i]<<" ";cout <<endl;
while( m-- ){
	cin >> d2 >> b;
	il = d2 - d1;
	w +=il;
	pocz = 0;
	kon = n + 1;
	for(i = 0; i < zbior.size();++i) {
		k = zbior[i];
		if( (w - wsp[k]) * gat[k] + h[k] <= b) pocz = k;
		else {
				kon = k;
				break;
				}
	}
	//cout <<"pocz= " << pocz <<" kon= " << kon <<endl;
	p = wyszukaj_bin(pocz,kon - 1,b);
	//cout <<"p= "<<p<<endl;
	wyn = 0;
	if(p <= n){		
		k2 = n + 1;
		for(i = zbior.size() - 1; i >=0; --i){
			k = zbior[i];
			if(k >= kon) {
				wyn += (k2 - k)*(h[k] - b)+ (w - wsp[k])*(pre[k2 - 1] - pre[k-1]) ;
				if(k > p){
					wsp[k] = h[k] = 0;
					zbior.pop_back();
				}
				else{
					wsp[k] =  w;
					h[k] = b;
				}
				k2 = k;
			}				
			else break;
		}
		if(p < k2){
			wyn += 	(h[pocz] - b)*(k2 - p) + (w - wsp[pocz])*(pre[k2 - 1] - pre[p-1]) ;
			zbior.push_back(p);
			h[p] = b;
			wsp[p] = w;
			}
		//cout <<"zbior ";for(j = 0; j < zbior.size();++j) cout << zbior[j] << " " ; cout << endl;
	}
	cout << wyn << endl;
	d1 = d2;
}

    return 0;
}