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
| #include<bits/stdc++.h> #define I inline #define W while #define RI register int #define Cn const #define CI Cn int& #define gc getchar #define pc putchar #define LL long long using namespace std; I void read(int& x){RI f=1;char c=gc();x=0;W(!('0'<=c&&c<='9')) f=c^'-'?f:-1,c=gc();W('0'<=c&&c<='9') x=x*10+(c-'0'),c=gc();x*=f;} I void write(LL x){x<0&&(pc('-'),x=-x),x>=10&&(write(x/10),0),pc(x%10+'0');} Cn int N=1e6+10; int n,m,inf=2e9,cnt; #define P pair<LL,int> #define MP make_pair #define fi first #define se second P b[N<<1]; LL sc,Ans; priority_queue<LL> Q1; priority_queue<P> Q2; int main(){ RI i,j,x,y;LL t;for(read(n),read(m),i=1;i<=n;i++) read(x),b[++cnt]=MP(x,-1); for(i=1;i<=m;i++) read(x),read(y),b[++cnt]=MP(x,y),sc+=y; if(sc<n) return puts("-1"),0; for(sort(b+1,b+cnt+1),i=1;i<=cnt;i++) if(~b[i].se){ W(!Q1.empty()&&b[i].se&&b[i].fi<Q1.top()) t=b[i].fi-Q1.top(),Q1.pop(),b[i].se--,Q2.push(MP(b[i].fi+t,0)),Ans+=t; b[i].se&&(b[i].se--,Q2.push(MP(b[i].fi,i)),0); }else{ t=2e12;if(!Q2.empty()) t=b[i].fi-Q2.top().fi,j=Q2.top().se,Q2.pop(),b[j].se&&(b[j].se--,Q2.push(MP(b[j].fi,j)),0); Ans+=t,Q1.push(b[i].fi+t); }return write(Ans),0; }
|