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
#include<iostream>
#include<algorithm>
#include<vector>
#define st first
#define nd second
#define mp make_pair
#define LL long long
#define pb push_back
using namespace std;
int a[500000],n;
LL pref[500000];
LL suma(int x,int y){
	if(x==0)return pref[y];
	return pref[y]-pref[x-1];	
}
vector<int>pocz;
vector<LL>wys,dzien;
LL res(LL d,LL h){
	LL wyn=0,pos=n-1;
	int x;
	while(pocz.size()>1){
		x=pocz.size()-1;
		if(wys[x]+(d-dzien[x])*a[pocz[x]]>h){
			wyn+=(LL)(pos-pocz[x]+1)*(wys[x]-h)+suma(pocz[x],pos)*(d-dzien[x]);
			pos=pocz[x]-1;
			pocz.pop_back();
			wys.pop_back();
			dzien.pop_back();
		}
		else break;
	}
	x=pocz.size()-1;
	int p=pocz[x],k=pos,sr;
	while(p+1<k){
		sr=(p+k)/2;
		LL rozm=(d-dzien[x])*a[sr]+wys[x];
		if(rozm>h)k=sr;
		else p=sr+1;
	}
	if((d-dzien[x])*a[p]+wys[x]>h)k=p;
	if((d-dzien[x])*a[k]+wys[x]<=h)k=pos+1;
	if(k==n)return wyn;
	if(k<=pos)wyn+=(LL)(pos+1-k)*(wys[x]-h)+suma(k,pos)*(d-dzien[x]);
	if(k==pocz[x]){
		pocz.pop_back();
		wys.pop_back();
		dzien.pop_back();
	}
	pocz.pb(k);
	wys.pb(h);
	dzien.pb(d);
	return wyn;
}
main(){
	ios_base::sync_with_stdio(0);
	int m;
	LL h=0,d=0;
	pocz.pb(0);
	wys.pb(0);
	dzien.pb(0);
	cin>>n>>m;
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	sort(a,a+n);
	pref[0]=a[0];
	for(int i=1;i<n;i++)pref[i]=pref[i-1]+a[i];
	for(int i=0;i<m;i++){
		cin>>d>>h;
		cout<<res(d,h)<<"\n";
	}
}