#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int tmp[100001], tmp2[100001];
void pakuri_sort(int N, int A[]) {
	const int b = 8;
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}

void pakuripair_sort(int N, int A[], int B[]) {
	const int b = 8;
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) {
			tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
			tmp2[kazu[A[i] >> k * b & ((1 << b) - 1)]] = B[i];
		}
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) {
			A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
			B[kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp2[i];
		}
	}
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	int N = getint(), M = getint();

	int A[100000];
	rep(i, N) A[i] = getint();
	pakuri_sort(N, A);

	int B[100000], C[100000];
	rep(i, M) {
		B[i] = getint();
		C[i] = getint();
	}
	pakuripair_sort(M, C, B);

	ll kotae = 0;
	int kazu = 0;
	for (int i = M - 1; i >= 0; i--) {
		int makkusu = min(B[i], N - kazu);
		rep(j, makkusu) kotae += max(A[kazu++], C[i]);
	}

	for (int i = kazu; i < N; i++) kotae += A[i];

	printf("%lld", kotae);

	Would you please return 0;
}


//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

void pakuri_sort(int N, int A[]) {
	const int b = 8;
	int tmp[100001];
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
	}
}

void pakuripair_sort(int N, int A[], int B[]) {
	const int b = 8;
	int tmp[100001], tmp2[100001];
	rep(k, 4) {
		int kazu[1 << b] = {}, kazu2[1 << b] = {};
		rep(i, N) kazu[A[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu[i + 1] += kazu[i];
		for (int i = N - 1; i >= 0; i--) {
			tmp[--kazu[A[i] >> k * b & ((1 << b) - 1)]] = A[i];
			tmp2[kazu[A[i] >> k * b & ((1 << b) - 1)]] = B[i];
		}
		k++;
		rep(i, N) kazu2[tmp[i] >> k * b & ((1 << b) - 1)]++;
		rep(i, (1 << b) - 1) kazu2[i + 1] += kazu2[i];
		for (int i = N - 1; i >= 0; i--) {
			A[--kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp[i];
			B[kazu2[tmp[i] >> k * b & ((1 << b) - 1)]] = tmp2[i];
		}
	}
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	int N = getint(), M = getint();

	int A[100000];
	rep(i, N) A[i] = getint();
	pakuri_sort(N, A);

	int B[100000],C[100000];
	rep(i, M) {
		B[i] = getint();
		C[i] = getint();
	}
	pakuripair_sort(M, C, B);

	ll kotae = 0;
	int kazu = 0;
	for (int i = M - 1; i >= 0; i--) {
		rep(j, B[i]) {
			if (kazu >= N) break;
			kotae += max(A[kazu], C[i]);
			kazu++;
		}
	}

	for (int i = kazu; i < N; i++) kotae += A[i];

	printf("%lld", kotae);

	Would you please return 0;
}


#include<bits/stdc++.h>
using namespace std;
void *wmem;
template<class T1, class T2> void sortA_L(int N, T1 a[], T2 b[], void *mem = wmem){
  int i;
  pair<T1, T2> *arr=(pair<T1, T2> *) mem;
  for(i=0;i<N;i++){
    arr[i].first = a[i];
    arr[i].second = b[i];
  }
  sort(arr, arr+N);
  for(i=0;i<N;i++){
    a[i] = arr[i].first;
    b[i] = arr[i].second;
  }
}
void sortF_L(int N, unsigned A[], void *mem = wmem){
  int bt, i, m, *sz;
  unsigned *arr, c;
  if(N < 256){
    sort(A, A+N);
    return;
  }
  bt = sizeof(unsigned) * 8;
  arr = (unsigned*)mem;
  sz = (int*)(arr+N);
  for(m=0;m<bt;m+=8){
    for(i=0;i<257;i++){
      sz[i] = 0;
    }
    for(i=0;i<N;i++){
      sz[ 1+((A[i]>>m)&255u) ]++;
    }
    for(i=1;i<257;i++){
      sz[i] += sz[i-1];
    }
    for(i=0;i<N;i++){
      c = ((A[i]>>m)&255u);
      arr[sz[c]++] = A[i];
    }
    swap(A, arr);
  }
}
void sortF_L(int N, int A[], void *mem = wmem){
  int *arr, i, x, y, z;
  unsigned *send;
  if(N < 256){
    sort(A, A+N);
    return;
  }
  send = (unsigned*)A;
  sortF_L(N, send, mem);
  if(A[0] < 0 || A[N-1] >= 0){
    return;
  }
  x = 0;
  y = N;
  while(x < y){
    z = (x+y) / 2;
    if(A[z] < 0){
      y = z;
    }
    else{
      x = z+1;
    }
  }
  arr = (int*)mem;
  z = 0;
  for(i=x;i<N;i++){
    arr[z++] = A[i];
  }
  for(i=0;i<x;i++){
    arr[z++] = A[i];
  }
  for(i=0;i<N;i++){
    A[i] = arr[i];
  }
}
void sortF_L(int N, unsigned long long A[], void *mem = wmem){
  int bt, i, m, *sz;
  unsigned c;
  unsigned long long *arr;
  if(N < 512){
    sort(A, A+N);
    return;
  }
  bt = sizeof(unsigned long long) * 8;
  arr = (unsigned long long*)mem;
  sz = (int*)(arr+N);
  for(m=0;m<bt;m+=8){
    for(i=0;i<257;i++){
      sz[i] = 0;
    }
    for(i=0;i<N;i++){
      sz[ 1+((A[i]>>m)&255u) ]++;
    }
    for(i=1;i<257;i++){
      sz[i] += sz[i-1];
    }
    for(i=0;i<N;i++){
      c = ((A[i]>>m)&255u);
      arr[sz[c]++] = A[i];
    }
    swap(A, arr);
  }
}
void sortF_L(int N, long long A[], void *mem = wmem){
  int i, x, y, z;
  long long *arr;
  unsigned long long *send;
  if(N < 512){
    sort(A, A+N);
    return;
  }
  send = (unsigned long long*)A;
  sortF_L(N, send, mem);
  if(A[0] < 0 || A[N-1] >= 0){
    return;
  }
  x = 0;
  y = N;
  while(x < y){
    z = (x+y) / 2;
    if(A[z] < 0){
      y = z;
    }
    else{
      x = z+1;
    }
  }
  arr = (long long*)mem;
  z = 0;
  for(i=x;i<N;i++){
    arr[z++] = A[i];
  }
  for(i=0;i<x;i++){
    arr[z++] = A[i];
  }
  for(i=0;i<N;i++){
    A[i] = arr[i];
  }
}
inline void rd(int &x){
  int k, m=0;
  x=0;
  for(;;){
    k = getchar_unlocked();
    if(k=='-'){
      m=1;
      break;
    }
    if('0'<=k&&k<='9'){
      x=k-'0';
      break;
    }
  }
  for(;;){
    k = getchar_unlocked();
    if(k<'0'||k>'9'){
      break;
    }
    x=x*10+k-'0';
  }
  if(m){
    x=-x;
  }
}
inline void wt_L(char a){
  putchar_unlocked(a);
}
inline void wt_L(long long x){
  char f[20];
  int m=0, s=0;
  if(x<0){
    m=1;
    x=-x;
  }
  while(x){
    f[s++]=x%10;
    x/=10;
  }
  if(!s){
    f[s++]=0;
  }
  if(m){
    putchar_unlocked('-');
  }
  while(s--){
    putchar_unlocked(f[s]+'0');
  }
}
char memarr[96000000];
int N;
int M;
int A[100000];
int B[100000];
int C[100000];
int main(){
  int i, j, k;
  long long res;
  wmem = memarr;
  rd(N);
  rd(M);
  {
    int Lj4PdHRW;
    for(Lj4PdHRW=0;Lj4PdHRW<N;Lj4PdHRW++){
      rd(A[Lj4PdHRW]);
    }
  }
  {
    int KL2GvlyY;
    for(KL2GvlyY=0;KL2GvlyY<M;KL2GvlyY++){
      rd(B[KL2GvlyY]);
      rd(C[KL2GvlyY]);
    }
  }
  sortF_L(N,A);
  sortA_L(M,C,B);
  i = 0;
  for(j=M-1;j>=0;j--){
    int Q5VJL1cS;
    for(Q5VJL1cS=0;Q5VJL1cS<B[j];Q5VJL1cS++){
      if(i==N || A[i] >= C[j]){
        break;
      }
      A[i++] = C[j];
    }
    if(i==N || A[i] >= C[j]){
      break;
    }
  }
  res = 0;
  for(i=0;i<N;i++){
    res += A[i];
  }
  wt_L(res);
  wt_L('\n');
  return 0;
}
// cLay varsion 20190526-1

// --- original code ---
// int N, M, A[1d5], B[1d5], C[1d5];
// {
//   int i, j, k;
//   ll res;
//
//   rd(N,M,A(N),(B,C)(M));
//   sortF(N,A);
//   sortA(M,C,B);
//
//   i = 0;
//   for(j=M-1;j>=0;j--){
//     rep(B[j]){
//       if(i==N || A[i] >= C[j]) break;
//       A[i++] = C[j];
//     }
//     if(i==N || A[i] >= C[j]) break;
//   }
//
//   res = 0;
//   rep(i,N) res += A[i];
//   wt(res);
// }


#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve()
{
    int n, m; cin >> n >> m;
    vector<ll> v(n);
    ll ans = 0;
    for (int i = 0; i < n; ++i) {
        cin >> v[i];
        ans += v[i];
    }
    sort(v.begin(), v.end());
    map<ll, ll, greater<ll>> vals;
    for (int i = 0; i < m; ++i) {
        ll b, c; cin >> b >> c;
        vals[c] += b;
    }
    int i = 0;
    for (auto it = vals.begin(); it != vals.end(); ++it) {
        ll val = it->first;
        ll count = it->second;
        while (v[i] < val && count-- > 0) {
            ans += val - v[i++];
        }
    }
    cout << ans << '\n';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve()
{
    int n, m; cin >> n >> m;
    vector<ll> v(n);
    ll ans = 0;
    for (int i = 0; i < n; ++i) {
        cin >> v[i];
        ans += v[i];
    }
    sort(v.begin(), v.end());
    map<ll, ll, greater<ll>> vals;
    for (int i = 0; i < m; ++i) {
        int b, c; cin >> b >> c;
        vals[c] += b;
    }
    int i = 0;
    for (auto it = vals.begin(); it != vals.end(); ++it) {
        int val = it->first;
        int count = it->second;
        while (v[i] < val && count-- > 0) {
            ans += val - v[i++];
        }
    }
    cout << ans << '\n';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
using ll = long long;

void solve()
{
    int n, m; cin >> n >> m;
    priority_queue<ll, vector<ll>, greater<ll>> q;
    for (int i = 0; i < n; ++i) {
        ll val; cin >> val;
        q.push(val);
    }
    for (int i = 0; i < m; ++i) {
        int b, c; cin >> b >> c;
        while (b-- > 0 && q.top() < c) {
            q.pop();
            q.push(c);
        }
    }
    ll ans = 0;
    while (!q.empty()) {
        ans += q.top();
        q.pop();
    }
    cout << ans << '\n';
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}


// AtCoder ABC127: D - Integer Cards
// 2019.9.8 bal4u

#include <stdio.h>
#include <stdlib.h>

typedef long long ll;

//// 高速入力
#if 1
int getchar_unlocked(void);
#define gc() getchar_unlocked()
#else
#define gc() getchar()
#endif

int in() {   // 非負整数の入力
	int n = 0, c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

typedef struct { int b, c; } T;
T t[100005];
int N, M;
int A[100005];

// a[i]>=key という条件を満たす最小のi
int lower_bound(int x) {
  int m, l = 0, r = N;
  while (l+1 < r) {
    m = (l+r) >> 1;
    if (A[m] < x) l = m; else r = m;
  }
  return A[l] < x? r: l;
}

int cmp_a(const void *u, const void *v) { return *(int *)u - *(int *)v; }
int cmp_t(const void *u, const void *v) {
	int t;
	if (t = ((T *)v)->c - ((T *)u)->c) return t;
	return ((T *)v)->b - ((T *)u)->b;
}

inline static ll sum(int l, int r) { ll s = 0; while (l < r) s += A[l++]; return s; }

int main()
{
	int i, w, pos; ll ans;

	N = in(), M = in();
	for (i = 0; i < N; i++) A[i] = in();
	qsort(A, N, sizeof(int), cmp_a);
	for (i = 0; i < M; i++) t[i].b = in(), t[i].c = in();
	qsort(t, M, sizeof(T), cmp_t);

	w = 0;
	for (i = 0; i < M && w < N; i++) {
		pos = lower_bound(t[i].c) - w;
		if (pos <= 0) break;
		if (t[i].b > pos) t[i].b = pos;
		w += t[i].b;
	}

	ans = 0, pos = 0;
	while (--i >= 0) ans += (ll)t[i].b * t[i].c, pos += t[i].b;
	ans += sum(pos, N);
	printf("%lld\n", ans);
	return 0;
}


#include <stdio.h>

void quicksort(int array[], int left, int right) {
    int l = left;
    int r = right;
    int pivot = array[(left + right) / 2]; // 中央からピボットを選択
    int buf;

    while (1) {
        while (array[l] < pivot) l++;
        while (array[r] > pivot) r--;

        if (l > r) break;

        // pivotより小さい値を左、大きい値を右に入れ替え
        buf = array[l];
        array[l] = array[r];
        array[r] = buf;

        l++, r--;
    };

    // pivotより小さい領域と大きい領域をそれぞれ再帰的にソート
    if (left < r)  quicksort(array, left, r);
    if (l < right) quicksort(array, l, right);
}

void quicksort2(int array[],int array2[], int left, int right) {
    int l = left;
    int r = right;
    int pivot = array[(left + right) / 2]; // 中央からピボットを選択
    int buf;

    while (1) {
        while (array[l] < pivot) l++;
        while (array[r] > pivot) r--;

        if (l > r) break;

        // pivotより小さい値を左、大きい値を右に入れ替え
        buf = array[l];
        array[l] = array[r];
        array[r] = buf;
        buf = array2[l];
        array2[l] = array2[r];
        array2[r] = buf;

        l++, r--;
    };

    // pivotより小さい領域と大きい領域をそれぞれ再帰的にソート
    if (left < r)  quicksort2(array,array2, left, r);
    if (l < right) quicksort2(array,array2, l, right);
}

int main(){
  int n,m;
  scanf("%d %d",&n,&m);
  int a[100000],b[100000],c[100000];
  for(int i=0;i<n;i++){
    scanf("%d",&a[i]);
  }
  for(int i=0;i<m;i++){
    scanf("%d %d",&b[i],&c[i]);
  }
  quicksort(a,0,n-1);
  quicksort2(c,b,0,m-1);
  int i=0;
  for(int j=m-1;j>=0;j--){
    for(int k=0;k<b[j];k++) {
      if(a[i]>c[j]) break;
      if(i>=n)goto res;
      a[i++]=c[j];
    }
  }
  long long sum=0;
  res:

  for(int j=0;j<n;j++) sum += a[j];
  printf("%lld",sum);
  return 0;
}


#include <stdio.h>
#define INPUTNUM 100000

typedef struct a{
    int b;
    int c;
}Data;

void marge_sub1(Data a[], Data work[], int start, int end){
  if(end - start > 0){
    //要素が2個以上なら分割し、その後併合
    //2分割したとき後ろ側に来る配列の先頭は もとの配列の開始番号と終了番号の平均 + 1
    int bstart = start + (end - start)/2 + 1;
    int i = start;
    int j = start;
    int k = bstart;

    marge_sub1(a, work, start, bstart - 1);
    marge_sub1(a, work, bstart, end);

    //2分割した配列の先頭にある要素を比較し、小さい方をとる
    while(1){
      if(work[j].c <= work[k].c){
	a[i++] = work[j++];
	if(j >= bstart){
	  break;
	}
      }else{
	a[i++] = work[k++];
	if(k > end){
	  break;
	}
      }
    }

    if(k > end){
      while(i <= end){
	a[i++] = work[j++];
      }
    }else if(j >= bstart){
      while(i <= end){
	a[i++] = work[k++];
      }
    }

    for(i = start; i <= end; i++){
      work[i] = a[i];
    }

  }else{
    //要素が1個ならそれを作業用配列にコピーし、処理を戻す
    work[start] = a[start];
  }
}

void margesort1(Data a[], int start, int end){
  if(end - start > 0){
    Data work[INPUTNUM];
    int bstart = start + (end - start)/2 + 1;
    int i = start;
    int j = start;
    int k = bstart;

    marge_sub1(a, work, start, bstart - 1);
    marge_sub1(a, work, bstart, end);

    //2分割した配列の先頭にある要素を比較し、小さい方をとる
    while(1){
        if(work[j].c <= work[k].c){
        a[i++] = work[j++];
        if(j >= bstart){
          break;
        }
          }else{
        a[i++] = work[k++];
        if(k > end){
          break;
        }
          }
        }

        if(k > end){
          while(i <= end){
        a[i++] = work[j++];
          }
        }else if(j >= bstart){
          while(i <= end){
        a[i++] = work[k++];
          }
    }
  }
}

void marge_sub(int a[], int work[], int start, int end){
  if(end - start > 0){
    //要素が2個以上なら分割し、その後併合
    //2分割したとき後ろ側に来る配列の先頭は もとの配列の開始番号と終了番号の平均 + 1
    int bstart = start + (end - start)/2 + 1;
    int i = start;
    int j = start;
    int k = bstart;

    marge_sub(a, work, start, bstart - 1);
    marge_sub(a, work, bstart, end);

    //2分割した配列の先頭にある要素を比較し、小さい方をとる
    while(1){
      if(work[j] <= work[k]){
	a[i++] = work[j++];
	if(j >= bstart){
	  break;
	}
      }else{
	a[i++] = work[k++];
	if(k > end){
	  break;
	}
      }
    }

    if(k > end){
      while(i <= end){
	a[i++] = work[j++];
      }
    }else if(j >= bstart){
      while(i <= end){
	a[i++] = work[k++];
      }
    }

    for(i = start; i <= end; i++){
      work[i] = a[i];
    }

  }else{
    //要素が1個ならそれを作業用配列にコピーし、処理を戻す
    work[start] = a[start];
  }
}

void margesort(int a[], int start, int end){
  if(end - start > 0){
    int work[INPUTNUM];
    int bstart = start + (end - start)/2 + 1;
    int i = start;
    int j = start;
    int k = bstart;

    marge_sub(a, work, start, bstart - 1);
    marge_sub(a, work, bstart, end);

    //2分割した配列の先頭にある要素を比較し、小さい方をとる
    while(1){
        if(work[j] <= work[k]){
        a[i++] = work[j++];
        if(j >= bstart){
          break;
        }
          }else{
        a[i++] = work[k++];
        if(k > end){
          break;
        }
          }
        }

        if(k > end){
          while(i <= end){
        a[i++] = work[j++];
          }
        }else if(j >= bstart){
          while(i <= end){
        a[i++] = work[k++];
          }
    }
  }
}

int main(void){
    int n,m;
    int a[INPUTNUM];
    Data d[INPUTNUM];
    int i,j,k;
    long long int sum;

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

    for(i = 0; i < m; i++){
        scanf("%d %d", &(d[i].b), &(d[i].c));
    }

    margesort(a, 0, n - 1);
    margesort1(d, 0, m - 1);
    sum = 0;
    i = 0;
    j = m - 1;
    while(i < n && j >= 0){
        for(k = d[j].b; k > 0; k--){
            if(a[i] < d[j].c){
                a[i] = d[j].c;
                i++;
            }else{
                break;
            }
        }
        if(k > 0){
            break;
        }
        j--;
    }

    for(i = 0; i < n; i++){
        sum += a[i];
    }

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

    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
typedef long long LL;
typedef long double Lf;
#define Rep(i,a,n)for(int i=(int)(a);i<(int)(n);i++)
#define rep(i,n)Rep(i,0,n)
#define Ma(x,y) ((x)>(y)?(x):(y))
#define mi(x,y) ((x)<(y)?(x):(y))
#define N 11//提出時確認
#define MOD 1000000007
int acs(const void* a, const void* b) { return *(int*)a - *(int*)b; } //1,2,3,4
int des(const void* a, const void* b) { return *(int*)b - *(int*)a; }
int cmp_char(const void* a, const void* b) { return *(char*)a - *(char*)b; } //a,b,c,d
int cmp_str(const void* a, const void* b) { return strcmp(*(const char**)a, *(const char**)b); } //aaa,aab
//temmie_のsnippet

typedef struct BC { int b; int c; }BC;
int cmp_BC(const void* a, const void* b) { return ((BC*)b)->c - ((BC*)a)->c; }//BCのcの大きい方から

int main() {
	int n,m,x=0,a[N]; LL ans=0; BC q[N];
	scanf("%d%d",&n,&m);
	rep(i,n)scanf("%d",a+i);
	rep(i,m)scanf("%d%d",&q[i].b,&q[i].c);

	qsort(a,n,sizeof(int),acs);//aは小さい方から
	qsort(q,m,sizeof(BC),cmp_BC);//cは大きい方から

	rep(i,m)rep(j,q[i].b){if(q[i].c<=a[x])break;a[x++]=q[i].c;}//書換
	rep(i,n)ans+=(LL)a[i];
	printf("%lld",ans);
	return 0;
}


#include<stdio.h>

int main(void){
    int n,m,b,c,tmp,i,j,s,t,x;
    int changeN;
    long long sam = 0;
    scanf("%d %d",&n,&m);
    int a[n-1];

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

    for(i = 1; i <= m; i++){
        quick_sort(a, 0, n-1);

        scanf("%d %d",&b,&c);
        for(changeN = 0, j= 0; changeN < b && j <= n -1; j++){
            if(a[j] < c){
                a[j] = c;
                changeN ++;
            }
        }
    }

    for(i =0;i <= n -1; i++){
        sam = sam + a[i];
    }
    printf("%lld\n",sam);
}

void swap (int *x, int *y) {
  int temp;    // 値を一時保存する変数

  temp = *x;
  *x = *y;
  *y = temp;
}

int partition (int array[], int left, int right) {
  int i, j, pivot;
  i = left;
  j = right + 1;
  pivot = left;   // 先頭要素をpivotとする

  do {
    do { i++; } while (array[i] < array[pivot]);
    do { j--; } while (array[pivot] < array[j]);
    // pivotより小さいものを左へ、大きいものを右へ
    if (i < j) { swap(&array[i], &array[j]); }
  } while (i < j);

  swap(&array[pivot], &array[j]);   //pivotを更新

  return j;
}

/* クイックソート */
void quick_sort (int array[], int left, int right) {
  int pivot;

  if (left < right) {
    pivot = partition(array, left, right);
    quick_sort(array, left, pivot-1);   // pivotを境に再帰的にクイックソート
    quick_sort(array, pivot+1, right);
  }
}


#include<stdio.h>

int main(void){
    int n,m,b,c,tmp,i,j,s,t,x;
    int changeN;
    long long sam = 0;
    scanf("%d %d",&n,&m);
    int a[n-1];

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

    for(i = 1; i <= m; i++){
        for (s=0; s<= n - 1; ++s) {
            for (t=s+1; t<= n -1; ++t) {
                if (a[s] > a[t]) {
                tmp =  a[s];
                a[s] = a[t];
                a[t] = tmp;
                }
            }
        }
        scanf("%d %d",&b,&c);
        for(changeN = 0, j= 0; changeN < b && j <= n -1; j++){
            if(a[j] < c){
                a[j] = c;
                changeN ++;
            }
        }
    }

    for(i =0;i <= n -1; i++){
        sam = sam + a[i];
    }
    printf("%lld\n",sam);
}


// inputに入力データ全体が入る
function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    input = input.split("\n");
    tmp0 = input[0].split(" ");
    N = Number(tmp0[0]);
    M = Number(tmp0[1]);
    A = input[1].split(" ").map(str => parseInt(str,10));
    // console.log(A)
    A = A.sort((a, b) => a-b)
    // console.log(A)

    BCdict=[]
    for(var i=1; i<=M;i++){
        tmp = input[i+1].split(" ")
        // tmp[0] // Bi
        // tmp[1] // Ci
        obj = {"value": Number(tmp[1]), "count": Number(tmp[0])}
        BCdict.push(obj)
    }
    // console.log(BCdict)
    BCdict = BCdict.sort((a,b) => b.value - a.value)
    // console.log(BCdict)

    // BCarray = []
    // for(var i=0; i < BCdict.length; i++)
    // {
    //     BCarray = BCarray.concat(Array.apply(null, Array(BCdict[i].count)).map(function(){return BCdict[i].value}))
    // }
    // // console.log(BCarray)

    // for(var i=0; i < BCarray.length; i++)
    // {
    //     if(BCarray[i] > A[i]){
    //         A[i] = BCarray[i]
    //     }else{
    //         break
    //     }
    // }

    dictIndex = 0
    dictCount = 0
    for(var i=0; i < A.length; i++)
    {
        var value = BCdict[dictIndex].value
        if(value > A[i])
        {
            A[i] = value
            dictCount++
            if(dictCount == BCdict[dictIndex].count){
                dictIndex++
                dictCount=0
                if(dictIndex == BCdict.length){
                    break
                }
            }
        }else{
            break
        }
    }

    var ans=0
    for(var i=0; i < A.length; i++)
    {
        ans += A[i]
    }
    console.log(ans)
  }
  //*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//   Main("3 2\n5 1 4\n2 3\n1 5\n");


"use strict";
function I(t,i){this._s=t.split("\n"),this._c=0,this._l=0,this._f=i||Number}I.prototype.a=function(t){var i=this._s[this._l];if(i){var s=i.trim().split(" "),h=s[this._c];return this._c++,s.length===this._c&&(this._c=0,this._l++),t?t(h):this._f(h)}},I.prototype.l=function(t){var i=this._s[this._l];if(i)return this._c=0,this._l++,i.split(" ").map(t||this._f)},module.exports=I;

function main(input) {
  var o = new I(input);

  var n = o.a();
  var m = o.a();
  var a = o.l();

  var arr = [];
  for (var i = 0; i < m; i++) {
    var b = o.a();
    var c = o.a();
    arr.push({b, c});
  }

  a.sort((a, b) => a - b);
  arr.sort((a, b) => a.c - b.c);

  var ans = [];
  while (ans.length < n) {
    var lastA = a[a.length - 1];
    var lastB = 0;
    if (arr.length > 0) {
      lastB = arr[arr.length - 1].c;
    }
    if (lastA >= lastB) {
      // console.log("A", {lastA})
      ans.push(lastA);
      a.pop();
    } else {
      // console.log("B", arr[arr.length - 1]);
      for (var j = 0; j < arr[arr.length - 1].b; j++) {
        ans.push(lastB);
      }
      arr.pop();
    }
  }

  console.log(ans.slice(0, n).reduce((acc, cur) => acc + cur));
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


module.exports=function(r){var t={};function n(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return r[e].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=r,n.c=t,n.d=function(r,t,e){n.o(r,t)||Object.defineProperty(r,t,{enumerable:!0,get:e})},n.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},n.t=function(r,t){if(1&t&&(r=n(r)),8&t)return r;if(4&t&&"object"==typeof r&&r&&r.__esModule)return r;var e=Object.create(null);if(n.r(e),Object.defineProperty(e,"default",{enumerable:!0,value:r}),2&t&&"string"!=typeof r)for(var o in r)n.d(e,o,function(t){return r[t]}.bind(null,o));return e},n.n=function(r){var t=r&&r.__esModule?function(){return r.default}:function(){return r};return n.d(t,"a",t),t},n.o=function(r,t){return Object.prototype.hasOwnProperty.call(r,t)},n.p="",n(n.s=0)}([function(r,t,n){n(1)(n(2).readFileSync("/dev/stdin","UTF-8").split("\n"))},function(r,t){function n(r,t){return function(r){if(Array.isArray(r))return r}(r)||function(r,t){var n=[],e=!0,o=!1,u=void 0;try{for(var i,f=r[Symbol.iterator]();!(e=(i=f.next()).done)&&(n.push(i.value),!t||n.length!==t);e=!0);}catch(r){o=!0,u=r}finally{try{e||null==f.return||f.return()}finally{if(o)throw u}}return n}(r,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}r.exports=function(r){for(var t=n(r[0].split(" ").map(function(r){return Number(r)}),2),e=t[0],o=t[1],u=r[1].split(" ").map(function(r){return Number(r)}),i=[],f=0;f<o;f++){var c=n(r[f+2].split(" ").map(function(r){return Number(r)}),2),l=c[0],a=c[1];i.push({b:l,c:a})}i.sort(function(r,t){return t.c-r.c}),u.sort(function(r,t){return r-t});for(var s=0,p=0;p<o&&!(s>=e||u[s]>=i[p].c);p++)for(lastb=i[p].b;lastb>0&&s<e&&!(u[s]>=i[p].c);)u[s]=i[p].c,s++,lastb--;for(var d=0,b=0;b<e;b++)d+=u[b];console.log(d)}},function(r,t){r.exports=require("fs")}]);


var natural={};

natural.successor=function(a){
    var ret=a.split(' ');
    for(var i=ret.length-1;i>=0;i--){
        if(ret[i]==='9'){
            ret[i]=0;
        }else{
            ret[i]=(ret[i]-0)+1+'';
            break;
        }
        if(i===0){
            ret.unshift('1');
        }
    }
    return ret.join('');
}

natural.add=function(...nums){//あまりにも多いnumsは扱えません
    var array=[];
    var max=0;
    nums.forEach(e=>{
        if(max<e.length){
            max=e.length;
        }
    });
    nums.forEach(e=>{
        array.push('0'.repeat(max-e.length)+e);
    });
    var temp;
    var ret='';
    var c=0;//繰り上がり
    for(var i=max-1;i>=0;i--){
        temp=c;
        array.forEach(e=>{
            temp+=(e[i]-0);
        });
        c=Math.floor(temp/10);
        ret=(temp%10)+ret;
    }
    return (c===0?'':c)+ret;
}

natural.subtract=function(a,b){
    if(this.isFormerLarger(b,a)){
        return false;
    }
    var l=b.length;
    var inversedB=b.split('').map(e=>{
        return 9-e;
    }).join('');
    while(inversedB[0]==='0'){
        inversedB=inversedB.slice(1);
    }
    var ret=natural.add(a,inversedB,'1').split('');
    for(var i=ret.length-l-1;i>=0;i--){
        if(ret[i]==='0'){
            ret[i]='9';
        }else{
            ret[i]=(ret[i]-1)+'';
            break;
        }
    }
    while(ret[0]==='0'){
        ret.shift();
    }
    return ret.join('')||'0';
}

natural.isFormerLarger=function(a,b){
    if(a.length>b.length){
        return true;
    }else if(a.length<b.length){
        return false;
    }
    for(var i=0;i<a.length;i++){
        if(a[i]>b[i]){
            return true;
        }else if(a[i]<b[i]){
            return false;
        }
    }
    return false;
}

natural.product=function(...nums){//あまりにも多いnumsは扱えません
    if(nums.some(e=>{return e==='0';})){
        return '0';
    }
    var pointer=new Array(nums.length);
    pointer.fill(0);
    var zeros=0;
    var array=[];
    var str;
    loop1:
    while(true){
        str=1;
        for(var i=0;i<nums.length;i++){
            str*=nums[i][nums[i].length-1-pointer[i]];
        }
        if(str!==0){
            str+='0'.repeat(zeros);
            array.push(str);
        }
        for(var i=0;i<pointer.length;i++){
            if(pointer[i]===nums[i].length-1){
                pointer[i]=0;
                zeros-=nums[i].length-1;
            }else{
                pointer[i]++;
                zeros++;
                break;
            }
            if(i===pointer.length-1){
                break loop1;
            }
        }
    }
    return natural.add(...array);
}

natural.divide=function(a,b){
    if(b==='0'){
        return false;
    }
    if(this.isFormerLarger(b,a)){
        return '0';
    }
    var workbench='';
    var vault=a+'';
    var ret='';
    do{
        workbench+=vault[0];
        vault=vault.slice(1);
        if(workbench==='0'){
            ret+='0';
            workbench='';
            continue;
        }
        for(var i=1;i<=10;i++){
            if(natural.isFormerLarger(natural.product(b,i+''),workbench)){
                if(i>1){
                    workbench=natural.subtract(workbench,natural.product((i-1)+'',b));
                }
                ret+=(i-1)+'';
                break;
            }else if(natural.product(b,i+'')===workbench){
                workbench='';
                ret+=i+'';
                break;
            }
        }
    }while(vault.length>0)
    while(ret[0]==='0'){
        ret=ret.slice(1);
    }
    return ret;
}

natural.mod=function(a,b){
    if(b==='0'){
        return false;
    }
    return natural.subtract(a,natural.product(b,natural.divide(a,b)));
}

natural.factorial=function(a){
    var ret='1';
    for(var i=2;i<=a;i++){
        ret=natural.product(ret,i+'');
    }
    return ret;
}

natural.power=function(a,b){
    if(a==='0'&&b==='0'){
        return false;
    }
    if(a==='0'){
        return '0';
    }
    if(b==='0'){
        return '1';
    }
    var array=[];
    var next;
    var flg;
    while(b!=='0'.repeat(b.length)){
        next=''
        flg=0;
        for(var i=0;i<b.length;i++){
            next+=Math.floor(b[i]/2)+flg;
            flg=(b[i]%2)*5;
        }
        array.push(flg===5);
        b=next;
    }
    var memo=[a];
    for(var i=1;i<array.length;i++){
        memo.push(natural.product(memo[memo.length-1],memo[memo.length-1]));
    }
    var elem=memo.filter((e,i)=>{
        return array[i];
    });
    return natural.product(...elem);
}

natural.lcm=function(...nums){
    var temp=nums[0];
    var a,b;
    for(var i=1;i<nums.length;i++){
        a=temp;
        b=nums[i];
        while(true){
            a=natural.mod(a,b);
            if(a==='0'){
                temp=natural.divide(natural.product(temp,nums[i]),b);
                break;
            }
            b=natural.mod(b,a);
            if(b==='0'){
                temp=natural.divide(natural.product(temp,nums[i]),a);
                break;
            }
        }
    }
    return temp;
}

var rational={};

rational.add=function(...nums){

}

function Main(input) {
  input=input.split("\n");
  if(input[input.length-1]===''){
    input.pop();
  }
  const N=input[0].split(' ')[0];
  //console.log(Math.log10(Number.MAX_SAFE_INTEGER));
  var nums=input.slice(2).map(e=>{
    return e.split(' ').map(f=>{
      return f-0;
    });
  });
  var array=input[1].split(' ').map(e=>{
    return e-0;
  }).sort((a,b)=>{
    return a-b;
  });
  var min;
  var max;
  var temp;//探す以下最大
  var mid;
  var deleteCount;
  nums.forEach(e=>{
    if(array[array.length-1]<=e[1]){
      temp=array.length-1;
    }else if(array[0]>e[1]){
      temp=-1;
    }else{
      min=0;
      max=array.length-1;
      while(max-min>1){
        mid=Math.floor((max+min)/2);
        if(array[mid]<=e[1]){
          min=mid;
        }else{
          max=mid;
        }
      }
      temp=min;
    }
    deleteCount=Math.min(e[0],temp+1,array.length);
    array=array.slice(deleteCount);
    array.splice(temp+1-deleteCount,0,...new Array(deleteCount).fill(e[1]));
  });
  console.log(array.reduce((acc,cur)=>{
    return acc+cur;
  }));
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

class PriorityQueue {
  constructor() {
    this.heap = [];
  }

  push(item) {
    let heap = this.heap;
    let i = heap.length++;
    let j;

    while(i) {
      j = Math.floor((i - 1) / 2);
      if(heap[j] <= item) break;
      heap[i] = heap[j]
      i = j;
    }

    heap[i] = item;
  }

  pop() {
    let heap = this.heap;
    let top = heap[0];
    let popped = heap.pop();

    let i = 0;
    let k = Math.floor(heap.length / 2);
    let j;

    while(i < k) {
      j = (i * 2) + 1;
      if(heap[j+1] < heap[j]) ++j;

      if(popped <= heap[j]) break;

      heap[i] = heap[j];

      i = j;
    }

    if(heap.length) {
      heap[i] = popped;
    }

    return top;
  }

  size() {
    return this.heap.length;
  }

  top() {
    return this.heap[0];
  }
}

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);

    const A = arg[1].split(" ").map(n=>parseInt(n));
    const B = arg.slice(2, M + 2).map(n=>n.split(" ").map(l=>parseInt(l)));

    let pq = new PriorityQueue();

    for(let i=0; i<N; i++) {
        pq.push(A[i]);
    }

    // console.log(pq.heap)

    for(let i=0; i<M; i++) {
        let target = B[i][0];
        let num = B[i][1];

        let temp = pq.top();

        for(let j=0; j<target; j++) {
            if(num > temp) {
                pq.pop();
                pq.push(num);
            } else {
                break;
            }
        }
    }

    console.log(pq.heap.reduce((m,n)=>m+n));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";

class PriorityQueue {
  constructor() {
    this.heap = [];
  }

  push(item) {
    let heap = this.heap;
    let i = heap.length++;
    let j;

    while(i) {
      j = Math.floor((i - 1) / 2);
      if(heap[j] <= item) break;
      heap[i] = heap[j]
      i = j;
    }

    heap[i] = item;
  }

  pop() {
    let heap = this.heap;
    let top = heap[0];
    let popped = heap.pop();

    let i = 0;
    let k = Math.floor(heap.length / 2);
    let j;

    while(i < k) {
      j = (i * 2) + 1;
      if(heap[j+1] < heap[j]) ++j;

      if(popped <= heap[j]) break;

      heap[i] = heap[j];

      i = j;
    }

    if(heap.length) {
      heap[i] = popped;
    }

    return top;
  }

  size() {
    return this.heap.length;
  }

  top() {
    return this.heap[0];
  }
}

const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0].split(" ")[0]);
    const M = parseInt(arg[0].split(" ")[1]);

    const A = arg[1].split(" ").map(n=>parseInt(n));
    const B = arg.slice(2, M + 2).map(n=>n.split(" ").map(l=>parseInt(l)));

    let pq = new PriorityQueue();

    for(let i=0; i<N; i++) {
        pq.push(A[i]);
    }

    // console.log(pq.heap)

    for(let i=0; i<M; i++) {
        let target = B[i][0];
        let num = B[i][1];

        let temp = pq.top();

        for(let j=0; j<target; j++) {
            if(num > temp) {
                pq.pop();
                pq.push(num);
            }
        }
    }

    console.log(pq.heap.reduce((m,n)=>m+n));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

const (
	initialBufSize = 1e4
	maxBufSize     = 1e6 + 7
)

var buf []byte = make([]byte, maxBufSize)
var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(buf, maxBufSize)
}

type cards struct {
	B int
	C int
}

type SortByC []cards

func (a SortByC) Len() int           { return len(a) }
func (a SortByC) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a SortByC) Less(i, j int) bool { return a[i].C > a[j].C }

func main() {
	N, M := nextInt(), nextInt()
	An := make([]int, N)
	c := make([]cards, M)
	for i := 0; i < N; i++ {
		An[i] = nextInt()
	}
	for i := 0; i < M; i++ {
		c[i].B = nextInt()
		c[i].C = nextInt()
	}
	sort.Ints(An)
	sort.Sort(SortByC(c))
	var ans, index int
	for i := 0; i < N; i++ {
		if index == len(c) {
			ans += An[i]
		} else {
			ans += MaxOf(An[i], c[index].C)
			c[index].B--
			if c[index].B == 0 {
				index++
			}
		}
	}
	fmt.Println(ans)
}

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func abs(a int) int {
	if a > 0 {
		return a
	} else {
		return -a
	}
}

func pow(p, q int) int {
	res := p
	if q == 0 {
		return 1
	}
	for i := 0; i < q-1; i++ {
		res *= p
	}
	return res
}

func MinOf(vars ...int) int {
	min := vars[0]
	for _, i := range vars {
		if min > i {
			min = i
		}
	}
	return min
}

func MaxOf(vars ...int) int {
	max := vars[0]
	for _, i := range vars {
		if max < i {
			max = i
		}
	}
	return max
}

func gcdof2numbers(a int, b int) int {
	if b == 0 {
		return a
	}
	return gcdof2numbers(b, a%b)
}

func lcmof2numbers(a int, b int) int {
	return a / gcdof2numbers(a, b) * b
}

// マイナスの場合は考慮していない
func fuctorial(a int) int {
	if a == 1 || a == 0 {
		return 1
	} else {
		return fuctorial(a-1) * a
	}
}

func NextPermutation(x sort.Interface) bool {
	n := x.Len() - 1
	if n < 1 {
		return false
	}
	j := n - 1
	for ; !x.Less(j, j+1); j-- {
		if j == 0 {
			return false
		}
	}
	l := n
	for !x.Less(j, l) {
		l--
	}
	x.Swap(j, l)
	for k, l := j+1, n; k < l; {
		x.Swap(k, l)
		k++
		l--
	}
	return true
}

// 素因数分解したmapを返す
func primeFuctorize(n int) map[int]int {
	pf := map[int]int{}
	for i := 2; i*i <= n; i++ {
		for n%i == 0 {
			pf[i]++
			n /= i
		}
	}
	if n != 1 {
		pf[n]++
	}
	return pf
}

// ここから拝借
// https://shoman.hatenablog.com/entry/2020/02/25/185456
// Stackは[]intのエイリアス
type Stack []int

// Push adds an element
func (s *Stack) Push(v int) {
	*s = append(*s, v)
}

// Pop removes the top element and return it
func (s *Stack) Pop() (int, error) {
	if s.Empty() {
		return 0, fmt.Errorf("stack is empty")
	}

	v := (*s)[len(*s)-1]
	*s = (*s)[:len(*s)-1]
	return v, nil
}

// Peek returns the top value
func (s *Stack) Peek() (int, error) {
	if s.Empty() {
		return 0, fmt.Errorf("stack is empty")
	}

	return (*s)[len(*s)-1], nil
}

// Size returns the length of stack
func (s *Stack) Size() int {
	return len(*s)
}

// Empty returns true when stack is empty
func (s *Stack) Empty() bool {
	return s.Size() == 0
}

// NewStack generates stack
func NewStack() *Stack {
	s := new(Stack)
	return s
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	iv, _ := strconv.Atoi(sc.Text())
	return iv
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n, m := scanInt(), scanInt()
	as := make([]int, n)
	sum := 0
	for i := range as {
		as[i] = scanInt()
		sum += as[i]
	}
	sort.Ints(as)

	type card struct{ n, s int }
	cs := make([]card, m)
	for i := range cs {
		cs[i].s, cs[i].n = scanInt(), scanInt()
	}
	sort.Slice(cs, func(i, j int) bool { return cs[i].n > cs[j].n })

	p := 0
lb:
	for _, v := range cs {
		for i := 0; i < v.s; i++ {
			if p >= len(as) || v.n < as[p] {
				break lb
			}
			sum += v.n - as[p]
			p++
		}
	}
	fmt.Println(sum)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

var sc = bufio.NewScanner(os.Stdin)

const inf = 1 << 60

func ri() (n int) {
	sc.Scan()
	for _, v := range sc.Bytes() {
		n = n*10 + int(v-48)
	}
	return
}

type pair struct {
	b, c int
}

type byC []pair

func (p byC) Len() int { return len(p) }

func (p byC) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

func (p byC) Less(i, j int) bool { return p[i].c > p[j].c }

func larger(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func main() {
	sc.Split(bufio.ScanWords)
	n, m := ri(), ri()

	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = ri()
	}

	sort.Ints(a)

	q := make([]pair, m) // クエリ
	for i := 0; i < m; i++ {
		q[i] = pair{b: ri(), c: ri()}
	}

	// c で降順にソート
	sort.Sort(byC(q))

	ans := 0
	j := 0 // 限界値は m-1
	for i := 0; i < n; i++ {
		if j < m && q[j].c > a[i] {
			ans += q[j].c
			q[j].b--
			if q[j].b == 0 {
				j++
			}
		} else {
			ans += a[i]
		}
	}
	fmt.Println(ans)
}


package main

import (
	"bufio"
	"container/heap"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner((os.Stdin))

func nextLine() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	l := nextLine()
	i, e := strconv.Atoi(l)
	if e != nil {
		panic(e)
	}
	return i
}

func main() {
	sc.Split(bufio.ScanWords)
	N, M, A, CC := nextInt(), nextInt(), []int{}, []ChangeCard{}

	for i := 0; i < N; i++ {
		A = append(A, nextInt())
	}
	for i := 0; i < M; i++ {
		CC = append(CC, ChangeCard{nextInt(), nextInt()})
	}

	fmt.Printf("%d\n", ABC127D(A, CC))
}

// ABC127D ...
func ABC127D(A []int, CC []ChangeCard) (res int) {
	ih := &intSmallHeap{}
	heap.Init(ih)
	for i := 0; i < len(A); i++ {
		heap.Push(ih, A[i])
	}

	for i := 0; i < len(CC); i++ {
		for j := 0; j < CC[i].b; j++ {
			min := heap.Pop(ih).(int)
			if min < CC[i].c {
				heap.Push(ih, CC[i].c)
			} else {
				heap.Push(ih, min)
			}
		}
	}

	for ih.Len() > 0 {
		res += heap.Pop(ih).(int)
	}

	return
}

// ChangeCard ...
type ChangeCard struct {
	b int
	c int
}

type intSmallHeap []int

func (h intSmallHeap) Len() int           { return len(h) }
func (h intSmallHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h intSmallHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *intSmallHeap) Push(x interface{}) {
	*h = append(*h, x.(int))
}
func (h *intSmallHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	N, M := nextInt(), nextInt()
	As := nextInts(N)

	BCs := make([][]int, M)
	for i := 0; i < M; i++ {
		BCs[i] = nextInts(2)
	}

	sort.Ints(As)
	sort.Sort(BCS(BCs))

	i := 0
	for j := 0; j < M; j++ {
		B, C := BCs[j][0], BCs[j][1]
		if C <= As[i] {
			break
		}
		for B > 0 && i < len(As) && C > As[i] {
			As[i] = C
			B--
			i++
		}
	}

	fmt.Println(Sum(As...))
}

type BCS [][]int

func (bcs BCS) Len() int {
	return len(bcs)
}

func (bcs BCS) Less(i, j int) bool {
	return bcs[i][1] > bcs[j][1]
}

func (bcs BCS) Swap(i, j int) {
	bcs[i], bcs[j] = bcs[j], bcs[i]
}

func Sum(slice ...int) int {
	sum := 0
	for _, v := range slice {
		sum += v
	}
	return sum
}

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Buffer(make([]byte, 256), 1e9)
	sc.Split(bufio.ScanWords)
}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	N, M := nextInt(), nextInt()
	As := nextInts(N)

	BCs := make([][]int, M)
	for i := 0; i < M; i++ {
		BCs[i] = nextInts(2)
	}

	sort.Sort(sort.IntSlice(As))
	sort.Slice(BCs, func(i, j int) bool {
		return BCs[i][1] > BCs[j][1]
	})

	i := 0
	for j := 0; j < M; j++ {
		B, C := BCs[j][0], BCs[j][1]
		if C <= As[i] {
			break
		}
		for B > 0 && i < len(As) && C > As[i] {
			As[i] = C
			B--
			i++
		}
	}

	fmt.Println(Sum(As...))
}

func Sum(slice ...int) int {
	sum := 0
	for _, v := range slice {
		sum += v
	}
	return sum
}

func nextInts(n int) []int {
	ret := make([]int, n)
	for i := 0; i < n; i++ {
		ret[i] = nextInt()
	}
	return ret
}

var sc = bufio.NewScanner(os.Stdin)

func init() {
	sc.Buffer(make([]byte, 256), 1e9)
	sc.Split(bufio.ScanWords)
}

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	a, _ := strconv.Atoi(next())
	return a
}


n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i).sort
h = m.times.map{ gets.split.map(&:to_i) }
i = 0
h.sort_by{|u, v| -v}.each do |x, y|
  break if a[i] >= y

  x.times do
    a[i] = y
    i += 1
    break if i >= n
    break if a[i] >= y
  end
  break if i >= n
end

puts a.sum


n, m = gets.split.map(&:to_i)
a = gets.split.map(&:to_i).sort
h = []
m.times do
  h << gets.split.map(&:to_i)
end
i = 0
h.sort_by{|u, v| -v}.each do |x, y|
  break if a[i] >= y
  x.times do
    a[i] = y
    i += 1
    break if i >= n
    break if a[i] >= y
  end
  break if i >= n
end
puts a.inject(:+)


_  = gets.to_s.split.map(&:to_i)
a  = gets.to_s.split.map(&:to_i).sort
bcs = $<.read.split.map(&:to_i).each_slice(2).sort_by{|b,c| c}

ans = 0

b, c = bcs.pop
a.each do |k|

  if b && k < c
    ans += c
    b -= 1
    b,c = bcs.pop if b == 0
  else
    ans += k
  end
end

puts ans


n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
a.sort!
total = a.sum
h = Hash.new(0)
a.each { h[_1] += 1 }
d = []
x = Hash.new(0)
m.times do
  b, c = gets.chomp.split.map(&:to_i)
  x[c] += b
end
x.sort{|k1,k2| k1[1]<=>k2[1]}.each do |k, v|
  v.times { d << k }
  break if d.size > n
end
d.sort!.reverse!
[d.size, n].min.times do |i|
  break if a[i] > d[i]

  total = total + d[i] - a[i]
end

puts total


n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
a.sort!
total = a.sum
h = Hash.new(0)
a.each { h[_1] += 1 }
d = []
m.times do
  b, c = gets.chomp.split.map(&:to_i)
  b.times { d << c }
end
d.sort!.reverse!
[d.size, n].min.times do |i|
  break if a[i] > d[i]

  total = total + d[i] - a[i]
end

puts total


n, m = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
a.sort!
total = a.sum
h = Hash.new(0)
a.each do |_a|
  h[_a] += 1
end
x = Hash.new(0)
m.times do
  b, c = gets.chomp.split.map(&:to_i)
  x[c] += b
end
b = []
x = x.sort {|k1,k2| k1[1] <=> k2[1]}
x.each do |k, v|
  c = [n-b.size, v].min
  c.times{b << k}
  break if b.size >= n
end
b.sort!.reverse!
b.each_with_index do |c, i|
  break if a[i] >= c

  total = total + c - a[i]
end

puts total


/*------------------------------------------------------------------*/
/*------------------------- begin template -------------------------*/
/*------------------------------------------------------------------*/

// ref: tanakh <https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8>
// diff: using Parser
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut parser = Parser::from_str($s);
        input_inner!{parser, $($r)*}
    };
    (parser = $parser:ident, $($r:tt)*) => {
        input_inner!{$parser, $($r)*}
    };
    (new_stdin_parser = $parser:ident, $($r:tt)*) => {
        let stdin = std::io::stdin();
        let reader = std::io::BufReader::new(stdin.lock());
        let mut $parser = Parser::new(reader);
        input_inner!{$parser, $($r)*}
    };
    ($($r:tt)*) => {
        input!{new_stdin_parser = parser, $($r)*}
    };
}

macro_rules! input_inner {
    ($parser:ident) => {};
    ($parser:ident, ) => {};
    ($parser:ident, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($parser, $t);
        input_inner!{$parser $($r)*}
    };
}

macro_rules! read_value {
    ($parser:ident, ( $($t:tt),* )) => {
        ( $(read_value!($parser, $t)),* )
    };
    ($parser:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($parser, $t)).collect::<Vec<_>>()
    };
    ($parser:ident, chars) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()
    };
    ($parser:ident, char_) => {
        read_value!($parser, String).chars().collect::<Vec<char>>()[0]
    };
    ($parser:ident, usize1) => {
        read_value!($parser, usize) - 1
    };
    ($parser:ident, i64_) => {
        $parser.fast_i64()
    };
    ($parser:ident, usize_) => {
        $parser.fast_i64() as usize
    };
    ($parser:ident, usize1_) => {
        ($parser.fast_i64() - 1) as usize
    };
    ($parser:ident, $t:ty) => {
        $parser.next::<$t>().expect("Parse error")
    };
}

use std::io;
use std::io::BufRead;
use std::str;

// ref: tatsuya6502 <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e>
// ref: wariuni <https://qiita.com/tatsuya6502/items/cd448486f7ef7b5b8c7e#comment-7040a5ae96305e884eb9>
// diff: using std::io::BufRead::fill_buf()
pub struct Parser<R> {
    pub reader: R,
    buf: Vec<u8>,
    pos: usize,
}

impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}

impl<R: BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len, complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                (len, buf2[len - 1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return unsafe { str::from_utf8_unchecked(&self.buf[begin..end]) }.parse::<T>();
            } else {
                self.update_buf();
            }
        }
    }
    pub fn fast_i64(&mut self) -> i64 {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            if begin == self.buf.len() {
                self.update_buf();
                continue;
            }
            let mut res = 0;
            let (is_positive, mut end) = match self.buf[begin] {
                b'+' => (true, begin + 1),
                b'-' => (false, begin + 1),
                _ => (true, begin),
            };
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                res = res * 10 + (self.buf[end] as i64 - '0' as i64);
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return if is_positive { res } else { -res };
            } else {
                self.update_buf();
            }
        }
    }
}

#[allow(unused_imports)]
use std::cmp::*;
pub fn ungroup<T: PartialEq + Eq + Clone + Copy>(xs: &[(T, usize)]) -> Vec<T> {
    let mut res = vec![];
    for &(x, n) in xs.iter() {
        for _ in 0..n {
            res.push(x);
        }
    }
    res
}

fn main() {
    input! {
        new_stdin_parser = parser,
    }
    let res = solve(&mut parser);
    print!("{}", res);
}

/*------------------------------------------------------------------*/
/*-------------------------- end template --------------------------*/
/*------------------------------------------------------------------*/

use std::fmt::Write;
fn solve<R: BufRead>(parser: &mut Parser<R>) -> String {
    let mut buf = String::new();
    input! {
        parser = parser,
        n: usize,
        m: usize,
        xs: [i64; n],
        ys: [(usize,i64); m],
    }
    let mut xs = xs;
    xs.sort();
    let mut ys = ys;
    ys.sort_by(|&x, &y| x.1.cmp(&y.1));
    ys.reverse();
    let mut gs = vec![];
    let mut gs_wlen = 0;
    for &(b, c) in &ys {
        if gs_wlen > n {
            break;
        }
        gs.push((c, b));
        gs_wlen += b;
    }
    let zs = ungroup(&gs);
    let mut res = 0;
    for i in 0..n {
        if i < zs.len() {
            res += max(xs[i], zs[i]);
        } else {
            res += xs[i];
        }
    }
    writeln!(buf, "{}", res);
    buf
}


use std::cmp::*;
use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

pub fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let (n, m) = i.read::<(usize, usize)>();
    let a = i.read_vec::<usize>(n);
    let bc = i.read_vec::<(usize, usize)>(m);

    writeln!(o, "{}", solve(a, bc)).unwrap();
}
fn solve(mut a: Vec<usize>, mut bc: Vec<(usize, usize)>) -> usize {
    let len = a.len();
    bc.sort_by_key(|&(_b, c)| c);

    let mut used = 0;
    for &mut (ref mut b, c) in bc.iter_mut().rev() {
        *b = min(*b, len - used);
        for _ in 0..*b {
            a.push(c);
        }
        used += *b;
    }
    a.sort();
    a.reverse();
    a.iter().take(len).sum()

}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            let mut consume = 0;
            loop {
                self.r.consume(consume);
                let b = self.r.fill_buf().unwrap();
                assert!(b.len() != 0);
                if let Some(p) = b.iter().position(|&x| x == b' ' || x == b'\n') {
                    self.b.extend_from_slice(&b[..p]);
                    consume = p + 1;
                    break;
                }
                self.b.extend_from_slice(b);
                consume = b.len();
            }
            self.r.consume(consume);
            &self.b
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            if self.b.last() == Some(&b'\n') {
                &self.b[..self.b.len() - 1]
            } else {
                &self.b
            }
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpRead>(&mut self) -> T {
            T::cp_read(self)
        }

        pub fn read_vec<T: CpRead>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
    }
    pub trait CpRead {
        fn cp_read<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpRead for u64 {
        fn cp_read<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpRead for i64 {
        fn cp_read<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }

    macro_rules! cp_read_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpRead),*> CpRead for ($($t),*) {
                fn cp_read<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::cp_read(r)),*)
                }
            }
        };
    }

    macro_rules! cp_read_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpRead for $t_self {
                fn cp_read<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::cp_read(r) as $t_self
                }
            }
        };
    }
    macro_rules! cp_read_parse {
        ($t:ty) => {
            impl CpRead for $t {
                fn cp_read<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }

    cp_read_cast!(usize, u64);
    cp_read_cast!(u32, u64);
    cp_read_cast!(u16, u64);
    cp_read_cast!(i32, i64);
    cp_read_cast!(i16, i64);
    cp_read_cast!(i8, i64);

    cp_read_parse!(f64);

    cp_read_tuple!(T1, T2);
    cp_read_tuple!(T1, T2, T3);
    cp_read_tuple!(T1, T2, T3, T4);
    cp_read_tuple!(T1, T2, T3, T4, T5);

    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let mut idx = 0;
            let buf_len;
            {
                let buf = r.fill_buf().unwrap();
                buf_len = buf.len();
                assert!(buf_len != 0);
                while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {
                    value = value * 10 + (buf[idx] - b'0') as u64;
                    idx += 1;
                }
            }
            if idx < buf_len {
                r.consume(idx + 1);
                return value;
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let (consume, sign) = match r.fill_buf().unwrap()[0] {
            b'+' => (true, 1),
            b'-' => (true, -1),
            _ => (false, 1),
        };
        if consume {
            r.consume(1);
        }
        read_u64_fast(r) as i64 * sign
    }
}


#[doc = " https://github.com/hatoo/competitive-rust-snippets"]
#[allow(unused_imports)]
use std::cmp::{max, min, Ordering};
#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};
#[allow(unused_imports)]
use std::iter::FromIterator;
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }
#[macro_export]
macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut parser = Parser :: from_str ( $ s ) ; input_inner ! { parser , $ ( $ r ) * } } ; ( parser = $ parser : ident , $ ( $ r : tt ) * ) => { input_inner ! { $ parser , $ ( $ r ) * } } ; ( new_stdin_parser = $ parser : ident , $ ( $ r : tt ) * ) => { let stdin = std :: io :: stdin ( ) ; let reader = std :: io :: BufReader :: new ( stdin . lock ( ) ) ; let mut $ parser = Parser :: new ( reader ) ; input_inner ! { $ parser , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { input ! { new_stdin_parser = parser , $ ( $ r ) * } } ; }
#[macro_export]
macro_rules ! input_inner { ( $ parser : ident ) => { } ; ( $ parser : ident , ) => { } ; ( $ parser : ident , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ parser , $ t ) ; input_inner ! { $ parser $ ( $ r ) * } } ; }
#[macro_export]
macro_rules ! read_value { ( $ parser : ident , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ parser , $ t ) ) ,* ) } ; ( $ parser : ident , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ parser , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ parser : ident , chars ) => { read_value ! ( $ parser , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ parser : ident , usize1 ) => { read_value ! ( $ parser , usize ) - 1 } ; ( $ parser : ident , $ t : ty ) => { $ parser . next ::<$ t > ( ) . expect ( "Parse error" ) } ; }
use std::io;
use std::io::BufRead;
use std::str;
pub struct Parser<R> {
    reader: R,
    buf: Vec<u8>,
    pos: usize,
}
impl Parser<io::Empty> {
    pub fn from_str(s: &str) -> Parser<io::Empty> {
        Parser {
            reader: io::empty(),
            buf: s.as_bytes().to_vec(),
            pos: 0,
        }
    }
}
impl<R: BufRead> Parser<R> {
    pub fn new(reader: R) -> Parser<R> {
        Parser {
            reader: reader,
            buf: vec![],
            pos: 0,
        }
    }
    pub fn update_buf(&mut self) {
        self.buf.clear();
        self.pos = 0;
        loop {
            let (len, complete) = {
                let buf2 = self.reader.fill_buf().unwrap();
                self.buf.extend_from_slice(buf2);
                let len = buf2.len();
                if len == 0 {
                    break;
                }
                (len, buf2[len - 1] <= 0x20)
            };
            self.reader.consume(len);
            if complete {
                break;
            }
        }
    }
    pub fn next<T: str::FromStr>(&mut self) -> Result<T, T::Err> {
        loop {
            let mut begin = self.pos;
            while begin < self.buf.len() && (self.buf[begin] <= 0x20) {
                begin += 1;
            }
            let mut end = begin;
            while end < self.buf.len() && (self.buf[end] > 0x20) {
                end += 1;
            }
            if begin != self.buf.len() {
                self.pos = end;
                return str::from_utf8(&self.buf[begin..end]).unwrap().parse::<T>();
            } else {
                self.update_buf();
            }
        }
    }
}
#[allow(unused_macros)]
macro_rules ! debug { ( $ ( $ a : expr ) ,* ) => { eprintln ! ( concat ! ( $ ( stringify ! ( $ a ) , " = {:?}, " ) ,* ) , $ ( $ a ) ,* ) ; } }
#[doc = " https://github.com/hatoo/competitive-rust-snippets"]
const BIG_STACK_SIZE: bool = true;
#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}
fn solve() {
    input!{
        N:usize,M:usize,
        A:[usize;N],
        BC:[(usize,usize);M],
    }
    let mut a = A;
    a.sort(); // 昇順
    // dbg!(&a);
    let mut bc = BC;
    bc.sort_by_key(|&x| x.1); // cについて降順
    bc.reverse();
    // dbg!(&bc);

    let mut i = 0;
    'outer: for (b,c) in bc {
        for _ in 0..b {
            if a[i] >= c {
                break 'outer;
            }
            a[i] = c;
            i+=1;
            if i==a.len() {
                break 'outer;
            }
        }
    }
    let mut res = 0;
    for x in a {
        res+=x;
    }
    println!("{}",res);
}


// -*- coding:utf-8-unix -*-

extern crate lazy_static;
extern crate num_bigint;
// 0.2.2
extern crate num_traits;

// 0.2.8
use num_bigint::BigInt;
use num_traits::{one, zero, Num, NumAssignOps, NumOps, One, Pow, Zero};

// use proconio::derive_readable;
use proconio::fastout;
use proconio::input;
// use std::convert::TryInto;
use itertools::{assert_equal, concat};
use lazy_static::lazy_static;
// use libm::*;
use std::cmp::*;
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::*;
use std::mem::swap;
use std::ops::{BitAnd, Range, ShrAssign};
use std::str::FromStr;
use std::sync::Mutex;
use superslice::*;

// ##########
// read
// ###########
pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

// ##########
// chmin, chmax
// https://qiita.com/maguro_tuna/items/fab200fdc1efde1612e7
// ###########

#[allow(unused_macros)]
macro_rules! chmin {
    ($base:expr, $($cmps:expr),+ $(,)*) => {{
        let cmp_min = min!($($cmps),+);
        if $base > cmp_min {
            $base = cmp_min;
            true
        } else {
            false
        }
    }};
}

#[allow(unused_macros)]
macro_rules! chmax {
    ($base:expr, $($cmps:expr),+ $(,)*) => {{
        let cmp_max = max!($($cmps),+);
        if $base < cmp_max {
            $base = cmp_max;
            true
        } else {
            false
        }
    }};
}

#[allow(unused_macros)]
macro_rules! min {
    ($a:expr $(,)*) => {{
        $a
    }};
    ($a:expr, $b:expr $(,)*) => {{
        std::cmp::min($a, $b)
    }};
    ($a:expr, $($rest:expr),+ $(,)*) => {{
        std::cmp::min($a, min!($($rest),+))
    }};
}

#[allow(unused_macros)]
macro_rules! max {
    ($a:expr $(,)*) => {{
        $a
    }};
    ($a:expr, $b:expr $(,)*) => {{
        std::cmp::max($a, $b)
    }};
    ($a:expr, $($rest:expr),+ $(,)*) => {{
        std::cmp::max($a, max!($($rest),+))
    }};
}

// ##########
// lazy_static!
// ##########
// lazy_static! {
//     static ref H: Mutex<Vec<i32>> = Mutex::default();
//     static ref W: Mutex<Vec<i32>> = Mutex::default();
// }
// let mut values = VALUES.lock().unwrap();
// values.extend_from_slice(&[1, 2, 3, 4]);
// assert_eq!(&*values, &[1, 2, 3, 4]);

// const MOD: usize = 1000_000_000 + 7;

// ##########
// modint
// https://qiita.com/drken/items/3b4fdf0a78e7a138cd9a
// ##########

#[allow(dead_code)]
fn modinv<T: Num + NumAssignOps + NumOps + Copy + PartialOrd>(a: T, m: T) -> T {
    let mut a = a;
    let mut b = m;
    let mut u: T = one();
    let mut v: T = zero();

    while b != zero() {
        let t = a / b;
        a -= t * b;
        swap(&mut a, &mut b);
        u -= t * v;
        swap(&mut u, &mut v);
    }
    u %= m;
    if u < zero() {
        u += m;
    }
    return u;
}

#[test]
fn modinv_test() {
    assert_eq!(1, modinv(1, 13));
    assert_eq!(2, modinv(7, 13));
    assert_eq!(3, modinv(9, 13));
    assert_eq!(4, modinv(10, 13));
    assert_eq!(5, modinv(8, 13));
}

// long long modpow(long long a, long long n, long long mod) {
// long long res = 1;
// while (n > 0) {
// if (n & 1) res = res * a % mod;
// a = a * a % mod;
// n >>= 1;
// }
// return res;
// }
#[allow(dead_code)]
fn modpow<T>(a: T, n: T, modulo: T) -> T
where
    T: Num + NumAssignOps + NumOps + Copy + PartialOrd + BitAnd + PartialEq + ShrAssign,
    <T as BitAnd>::Output: PartialEq + Num,
{
    let mut res = one();
    let mut a = a;
    let mut n = n;
    while n > zero() {
        if (n & one()) == one() {
            res = res * a % modulo;
        }
        a = a * a % modulo;
        n >>= one();
    }

    return res;
}

#[test]
fn modpow_test() {
    assert_eq!(4, modpow(2, 2, 13));
    assert_eq!(3, modpow(2, 4, 13));
}

// 前処理 com_init(): O(n)
// クエリ処理 COM(n, k): O(1)
// conv::com_init();
// conv::com(n,k);
mod conv {
    use super::*;
    lazy_static! {
        static ref FAC: Mutex<Vec<usize>> = Mutex::default();
        static ref FINV: Mutex<Vec<usize>> = Mutex::default();
        static ref INV: Mutex<Vec<usize>> = Mutex::default();
        static ref MODULO: Mutex<usize> = Mutex::default();
        // static ref MAXNCONV: Mutex<usize> = Mutex::default();
    }

    // // テーブルを作る前処理
    // void com_init() {
    // fac[0] = fac[1] = 1;
    // finv[0] = finv[1] = 1;
    // inv[1] = 1;
    // for (int i = 2; i < MAX; i++){
    // fac[i] = fac[i - 1] * i % MOD;
    // inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
    // finv[i] = finv[i - 1] * inv[i] % MOD;
    // }

    #[allow(dead_code)]
    fn com_init_with(modulo: usize, maxn_conv: usize) {
        let mut fac = FAC.lock().unwrap();
        let mut finv = FINV.lock().unwrap();
        let mut inv = INV.lock().unwrap();
        *fac = vec![0; maxn_conv];
        *finv = vec![0; maxn_conv];
        *inv = vec![0; maxn_conv];

        let mut g_modulo = MODULO.lock().unwrap();
        *g_modulo = modulo;

        fac[0] = 1;
        fac[1] = 1;
        finv[0] = 1;
        finv[1] = 1;
        inv[1] = 1;

        for i in 2..maxn_conv {
            fac[i] = fac[i - 1] * i % modulo;
            inv[i] = modulo - inv[modulo % i] * (modulo / i) % modulo;
            finv[i] = finv[i - 1] * inv[i] % modulo;
        }
    }

    #[allow(dead_code)]
    pub fn com_init() {
        com_init_with(MOD, MAXN_CONV);
    }

    // // 二項係数計算
    // long long COM(int n, int k){
    // if (n < k) return 0;
    // if (n < 0 || k < 0) return 0;
    // return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
    // }
    #[allow(dead_code)]
    pub fn com(n: usize, k: usize) -> usize {
        let fac = FAC.lock().unwrap();
        let finv = FINV.lock().unwrap();
        // let mut inv = INV.lock().unwrap();
        let m = *MODULO.lock().unwrap();

        if n < k {
            return 0;
        }
        // if n < 0 || k < 0 {
        //     return 0;
        // }
        return fac[n] * (finv[k] * finv[n - k] % m) % m;
    }

    #[test]
    fn com_test() {
        com_init_with(13, 100);
        assert_eq!(12, com(12, 1));
        assert_eq!(66 % 13, com(12, 2));
        assert_eq!(220 % 13, com(12, 3));
        assert_eq!(495 % 13, com(12, 4));
        assert_eq!(792 % 13, com(12, 5));
        assert_eq!(924 % 13, com(12, 6));
        assert_eq!(com(12, 5), com(12, 7));
    }
}

// ##########
// union-find
// http://sntea.hatenablog.com/entry/2017/06/07/091246
// ##########

mod uf {
    // let mut uf = uf::UnionFind::new(10);
    // uf.unite; uf.same
    #[allow(dead_code)]
    struct UnionFind {
        par: Vec<usize>,
        rank: Vec<usize>,
    }

    impl UnionFind {
        #[allow(dead_code)]
        pub fn new(n: usize) -> UnionFind {
            let mut vec = vec![0; n];
            for i in 0..n {
                vec[i] = i;
            }
            UnionFind {
                par: vec,
                rank: vec![0; n],
            }
        }

        #[allow(dead_code)]
        fn find(&mut self, x: usize) -> usize {
            if x == self.par[x] {
                x
            } else {
                let par = self.par[x];
                let res = self.find(par);
                self.par[x] = res;
                res
            }
        }

        #[allow(dead_code)]
        pub fn same(&mut self, a: usize, b: usize) -> bool {
            self.find(a) == self.find(b)
        }

        #[allow(dead_code)]
        pub fn unite(&mut self, a: usize, b: usize) {
            let apar = self.find(a);
            let bpar = self.find(b);
            if self.rank[apar] > self.rank[bpar] {
                self.par[bpar] = apar;
            } else {
                self.par[apar] = bpar;
                if self.rank[apar] == self.rank[bpar] {
                    self.rank[bpar] += 1;
                }
            }
        }
    }

    #[test]
    fn union_find_test() {
        let mut uf = UnionFind::new(10);

        for i in 0..10 {
            for j in 0..10 {
                assert_eq!(i == j, uf.same(i, j));
            }
        }

        uf.unite(0, 1);
        assert_eq!(true, uf.same(0, 1));
        //false
        assert_eq!(false, uf.same(0, 9));
        assert_eq!(false, uf.same(1, 9));
        assert_eq!(false, uf.same(2, 9));

        uf.unite(8, 9);
        assert_eq!(true, uf.same(0, 1));
        assert_eq!(true, uf.same(8, 9));
        //false
        assert_eq!(false, uf.same(0, 9));
        assert_eq!(false, uf.same(1, 9));
        assert_eq!(false, uf.same(2, 9));

        uf.unite(1, 9);
        assert_eq!(true, uf.same(0, 1));
        assert_eq!(true, uf.same(8, 9));
        assert_eq!(true, uf.same(0, 8));
        assert_eq!(true, uf.same(0, 9));
        assert_eq!(true, uf.same(1, 8));
        assert_eq!(true, uf.same(1, 9));
        //false
        assert_eq!(false, uf.same(2, 9));
    }
}

// ###########
// seg_tree
// ant_book
// ###########
mod seg_tree {
    #[derive(Debug)]
    struct SegTree<T: Clone> {
        n: usize,
        dat: Vec<Option<T>>,
    }

    impl<T: Clone + std::fmt::Debug> SegTree<T> {
        #[allow(dead_code)]
        pub fn new(size: usize) -> SegTree<T> {
            let mut size_pow2 = 1;
            while size_pow2 < size {
                size_pow2 *= 2;
            }

            let dat: Vec<Option<T>> = vec![None; 2 * size_pow2 - 1];
            SegTree { n: size_pow2, dat }
        }

        #[allow(dead_code)]
        pub fn update<F: Fn(&Option<T>, &Option<T>) -> Option<T>>(
            &mut self,
            k: usize,
            a: T,
            update: F,
        ) {
            let mut k = k;
            k += self.n - 1;
            self.dat[k] = Some(a);
            while k > 0 {
                k = (k - 1) / 2;
                self.dat[k] = update(&self.dat[k * 2 + 1], &self.dat[k * 2 + 2]);
            }
        }

        #[allow(dead_code)]
        fn query_inner<F: Fn(&Option<T>, &Option<T>) -> Option<T>>(
            &self,
            selection_query: &F,
            a: usize,
            b: usize,
            k: usize,
            l: usize,
            r: usize,
        ) -> Option<T> {
            if r <= a || b <= l {
                // eprintln!("{}, {}, {}, {}, {:?}", a, b, l, r, "none");
                return None;
            }

            return if a <= l && r <= b {
                // eprintln!("{}, {}, {}, {}, {:?}", a, b, r, l, self.dat[k]);
                self.dat[k].clone()
            } else {
                let vl = self.query_inner(selection_query, a, b, k * 2 + 1, l, (l + r) / 2);
                let vr = self.query_inner(selection_query, a, b, k * 2 + 2, (l + r) / 2, r);

                selection_query(&vl, &vr)
            };
        }

        #[allow(dead_code)]
        pub fn query<F: Fn(&Option<T>, &Option<T>) -> Option<T>>(
            &self,
            selection_query: &F,
            a: usize,
            b: usize,
        ) -> Option<T> {
            return self.query_inner(selection_query, a, b, 0, 0, self.n);
        }
    }

    #[test]
    fn test_segtree_rmq() {
        let mut t: SegTree<usize> = SegTree::new(5);

        let cmp_f = |lhs: &Option<usize>, rhs: &Option<usize>| {
            if lhs.is_none() {
                return rhs.clone();
            }

            if rhs.is_none() {
                return lhs.clone();
            }

            return if lhs.unwrap() <= rhs.unwrap() {
                lhs.clone()
            } else {
                rhs.clone()
            };
        };
        // 1, 3, 2, 5, 1
        t.update(0, 1, cmp_f);
        t.update(1, 3, cmp_f);
        t.update(2, 2, cmp_f);
        t.update(3, 5, cmp_f);
        t.update(4, 1, cmp_f);
        // println!("{:?}", t);

        assert_eq!(1, t.query(&cmp_f, 0, 1).unwrap());
        assert_eq!(3, t.query(&cmp_f, 1, 2).unwrap());
        assert_eq!(2, t.query(&cmp_f, 2, 3).unwrap());
        assert_eq!(5, t.query(&cmp_f, 3, 4).unwrap());
        assert_eq!(1, t.query(&cmp_f, 4, 5).unwrap());

        // len2
        assert_eq!(1, t.query(&cmp_f, 0, 2).unwrap());
        assert_eq!(2, t.query(&cmp_f, 1, 3).unwrap());
        assert_eq!(2, t.query(&cmp_f, 2, 4).unwrap());
        assert_eq!(1, t.query(&cmp_f, 3, 5).unwrap());

        // len3
        assert_eq!(1, t.query(&cmp_f, 0, 3).unwrap());
        assert_eq!(2, t.query(&cmp_f, 1, 4).unwrap());
        assert_eq!(1, t.query(&cmp_f, 2, 5).unwrap());

        // len4
        assert_eq!(1, t.query(&cmp_f, 0, 4).unwrap());
        assert_eq!(1, t.query(&cmp_f, 1, 5).unwrap());

        // len5
        assert_eq!(1, t.query(&cmp_f, 0, 6).unwrap());
    }
}

// let mut values = VALUES.lock().unwrap();
// values.extend_from_slice(&[1, 2, 3, 4]);

// MOD, Combination関連に使う定数
#[allow(dead_code)]
const MOD: usize = 1000000007;
#[allow(dead_code)]
const MAXN_CONV: usize = 510000;

// #[fastout]
fn main() {
    input![n: usize, m:usize, mut a:[usize; n], mut bc:[(usize, usize); m]];

    a.sort();

    for (b, c) in bc.iter() {
        let bound = a.upper_bound(c);
        let len = min(*b, bound);
        for i in 0..len {
            a[i] = *c;
        }

        a.sort();
    }

    println!("{}", a.iter().sum::<usize>());
}


use proconio::{input, fastout};
use std::collections::BTreeMap;

#[fastout]
fn main() {
    input! {
        n: usize, m: usize,
        mut arr: [usize; n],
        rep: [(usize, usize); m],
    }

    arr.sort();

    let mut bset: BTreeMap<usize, usize> = BTreeMap::new();
    for &(b, c) in &rep {
        if bset.contains_key(&c) {
            let bb = bset.get_mut(&c).unwrap();
            *bb += b;
        } else {
            bset.insert(c, b);
        }
    }

    let mut cursor: usize = 0;
    for (&c, &b) in bset.iter().rev() {
        let m = std::cmp::min(n, b+cursor);
        if arr[m-1] >= c {
            for i in cursor..m {
                if arr[i] >= c { break; }
                arr[i] = c;
            }
            break;
        } else {
            for i in cursor..b+cursor { arr[i] = c; }
            cursor = m;
        }
    }

    println!("{}", arr.iter().sum::<usize>() );
}


use proconio::{input, fastout};
use std::collections::BTreeMap;

#[fastout]
fn main() {
    input! {
        n: usize, m: usize,
        mut arr: [usize; n],
        rep: [(usize, usize); m],
    }

    arr.sort();

    let mut bset: BTreeMap<usize, usize> = BTreeMap::new();
    for &(b, c) in &rep {
        if bset.contains_key(&c) {
            let bb = bset.get_mut(&c).unwrap();
            *bb += b;
        } else {
            bset.insert(c, b);
        }
    }

    let mut cursor: usize = 0;
    for (&c, &b) in bset.iter().rev() {
        if arr[b+cursor-1] >= c {
            for i in cursor..b+cursor {
                if arr[i] >= c { break; }
                arr[i] = c;
            }
            break;
        } else {
            for i in cursor..b+cursor { arr[i] = c; }
            cursor = b+cursor;
        }
    }

    println!("{}", arr.iter().sum::<usize>() );
}


let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let M = input[1]

let A = readLine()!.split(separator: " ").map { Int($0)! }.sorted()
var B: [[Int]] = []

for i in 0..<M {
  B.append(readLine()!.split(separator: " ").map { Int($0)! })
}

B = B.sorted { $0[1] > $1[1] }

var j = 0
var sum = 0

for i in 0..<A.count {
  if j < B.count && B[j][0] == 0 {
    j += 1
  }
  if j >= B.count || B[j][1] <= A[i] {
    sum += A[i]
  } else {
    B[j][0] -= 1
    sum += B[j][1]
  }
}
print(sum)


import Foundation

let args = readLine()!.split(separator: " ")
let N = Int(args[0])!
let M = Int(args[1])!

var minA = Int.max
var maxA = 0
var values: [Int: Int] = [:]

readLine()!.split(separator: " ").forEach {
    let a = Int($0)!
    values[a] = 1 + (values[a] ?? 0)
    minA = min(minA, a)
    maxA = max(maxA, a)
}

for _ in 1 ... M { // j
    let args = readLine()!.split(separator: " ")
    var b = Int(args[0])!
    let c = Int(args[1])!
    while b > 0 {
        let a = minA
        if a < c {
            let count = min(values[a]!, b)
            values[a]! -= count
            values[c] = count + (values[c] ?? 0)
            if values[a] == 0 {
                values[a] = nil
            }
            while values[minA] == nil {
                minA += 1
            }
            b -= count
        } else {
            b = 0
        }
    }
    maxA = max(maxA, c)
}

let answer = values.reduce(0, { $0 + $1.key * $1.value })

print(answer)


import Foundation

let args = readLine()!.split(separator: " ")
let N = Int(args[0])!
let M = Int(args[1])!
var A = readLine()!.split(separator: " ").map { Int($0)! }

A.sort()
for _ in 1 ... M { // j
    let args = readLine()!.split(separator: " ")
    let B = Int(args[0])!
    let C = Int(args[1])!
    var replace = 0
    for b in 0 ..< B {
        if C < A[b] { break }
        replace += 1
    }
    if 0 < replace {
        A.removeFirst(replace)
        var n = 0
        while n < N {
            if C <= A[n] { break }
            n += 1
        }
        for _ in 0 ..< replace {
            A.insert(C, at: n)
        }
    }
}
let answer = A.reduce(0, { $0 + $1 })

print(answer)


let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let M = input[1]

let A = readLine()!.split(separator: " ").map { Int($0)! }
var B: [[Int]] = []

for i in 0..<M {
  B.append(readLine()!.split(separator: " ").map { Int($0)! })
}

B = B.sorted { $0[1] > $1[1] }

var j = 0
var sum = 0

for i in 0..<A.count {
  if j < B.count && B[j][0] == 0 {
    j += 1
  }
  if j >= B.count || B[j][1] <= A[i] {
    sum += A[i]
  } else {
    B[j][0] -= 1
    sum += B[j][1]
  }
}
print(sum)


const log = console.log;

const createScanFunctions = (input: string) => {
  const str = input.trim();
  const len = str.length;
  let index = 0;

  const scan = () => {
    const startIndex = index;

    while (index < len) {
      const char = str[index];

      if (char === " " || char === "\n")
        return str.substring(startIndex, index++);

      index++;
    }

    return str.substr(startIndex);
  };

  const scanInt = () => parseInt(scan());

  return { scan, scanInt };
};

const scanIntArray = (scanIntFunction: () => number, length: number) => {
  const array = new Array<number>(length);
  for (let i = 0; i < length; i++) array[i] = scanIntFunction();

  return array;
};

// ----

const sumReducer = (accumulator: number, currentValue: number) =>
  accumulator + currentValue;
const sum = (numbers: number[]) => numbers.reduce(sumReducer, 0);

// ----

function Main(input: string): void {
  const { scanInt } = createScanFunctions(input);

  const n = scanInt();
  const m = scanInt();
  const a = scanIntArray(scanInt, n).sort((a, b) => a - b);

  const operations = new Array<number[]>(m);
  for (let i = 0; i < m; i++) operations[i] = [scanInt(), scanInt()]; // [b, c]
  operations.sort((opA, opB) => opB[1] - opA[1]);

  let aIndex = 0;

  for (let opIndex = 0; opIndex < m; opIndex++) {
    const [b, c] = operations[opIndex];
    let stop = false;

    for (let i = 0; i < b; i++) {
      if (a[aIndex] >= c) {
        stop = true;
        break;
      }

      a[aIndex++] = c;

      if (aIndex >= n) {
        stop = true;
        break;
      }
    }

    if (stop) break;
  }

  log(sum(a));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


import { readFileSync } from 'fs'

function main(input: string) {
  const [header, cards, ...lines] = input.split('\n').map(v => v.split(' ').map(Number))

  cards.sort((a, b) => a - b)
  lines.sort(([, a], [, b]) => b - a)

  let currentIndex = 0
  let currentCount = 0

  const getNextEnchant = (): number => {
    const value = lines[currentIndex]

    if (value == null) return 0

    const [maxCount, v] = value

    if (currentCount < maxCount) {
      ++currentCount
      return v
    }

    ++currentIndex
    currentCount = 0
    return getNextEnchant()
  }

  for (let i = 0, len = cards.length; i < len; ++i) {
    const enchant = getNextEnchant()
    if (enchant <= cards[i]) break

    cards[i] = enchant
  }

  const result = cards.reduce((sum, v) => sum + v, 0)

  console.log(result)
}

main(readFileSync('/dev/stdin', 'utf8').trim())


function main(input) {
  input = input.trim().split("\n");
  const [n, m] = input[0].split(" ").map(a => Number(a));
  const as = input[1].split(" ").map(a => Number(a));
  const bcs = input.slice(2).map(a => a.split(" ").map(b => Number(b)));
  as.sort((a, b) => a-b);
  bcs.sort((a, b) => b[1]-a[1]);
  const ds = [];
  for (let i = 0; i < m; i++) {
    if (n <= ds.length) break;
    const [b, c] = bcs[i];
    ds.push(...Array(b).fill(c));
  }
  let result = 0;
  for (let i = 0; i < n; i++) {
    const a = as[i];
    const d = ds[i];
    result += d ? Math.max(a, d) : a;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  input = input.trim().split("\n");
  const [n, m] = input[0].split(" ").map(a => Number(a));
  const as = input[1].split(" ").map(a => Number(a));
  const bcs = input.slice(2).map(a => a.split(" ").map(b => Number(b)));
  as.sort((a, b) => a-b);
  const ds = [];
  for (let i = 0; i < m; i++) {
    if (n <= ds.length) break;
    const [b, c] = bcs[i];
    ds.push(...Array(b).fill(c));
  }
  ds.sort((a, b) => b-a);
  let result = 0;
  for (let i = 0; i < n; i++) {
    const a = as[i];
    const d = ds[i];
    result += d ? Math.max(a, d) : a;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  input = input.trim().split("\n");
  const [n, m] = input[0].split(" ").map(a => Number(a));
  const as = input[1].split(" ").map(a => Number(a));
  const bcs = input.slice(2).map(a => a.split(" ").map(b => Number(b)));
  as.sort((a, b) => a-b);
  const ds = [];
  for (let i = 0; i < m; i++) {
    const [b, c] = bcs[i];
    ds.push(...Array(b).fill(c));
  }
  ds.sort((a, b) => b-a);
  let result = 0;
  for (let i = 0; i < n; i++) {
    const a = as[i];
    const d = ds[i];
    result += d ? Math.max(a, d) : a;
  }
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


const log = console.log;

const createScanFunctions = (input: string) => {
  const str = input.trim();
  const len = str.length;
  let index = 0;

  const scan = () => {
    const startIndex = index;

    while (index < len) {
      const char = str[index];

      if (char === " " || char === "\n")
        return str.substring(startIndex, index++);

      index++;
    }

    return str.substr(startIndex);
  };

  const scanInt = () => parseInt(scan());

  return { scan, scanInt };
};

const scanIntArray = (scanIntFunction: () => number, length: number) => {
  const array = new Array<number>(length);
  for (let i = 0; i < length; i++) array[i] = scanIntFunction();

  return array;
};

// ----

const createDigitArray = (v: number, capacity: number, base = 10) => {
  const array = new Array(capacity).fill(0);
  let i = 0;

  while (v > 0) {
    array[i] = v % base;
    v = (v / base) | 0;
    i += 1;
  }

  return array;
};

const addDigitArrays = (src: number[], dest: number[]) => {
  const len = dest.length - 1;

  for (let i = 0; i < len; i++) dest[i] += src[i];
};

const fixDigitArray = (array: number[], base = 10) => {
  const len = array.length - 1;

  for (let i = 0; i < len; i++) {
    array[i + 1] += (array[i] / base) | 0;
    array[i] = array[i] % base;
  }
};

const digitArrayToString = (array: number[]) => {
  const len = array.length;

  let i = len - 1;
  let str = "";

  while (i >= 0) {
    if (str !== "" || array[i] !== 0) {
      str += array[i];
    }

    i--;
  }

  return str;
};

// ----

function Main(input: string): void {
  const { scanInt } = createScanFunctions(input);

  const n = scanInt();
  const m = scanInt();

  let a = scanIntArray(scanInt, n).sort((a, b) => a - b);
  const operations = new Array<number[]>(m);

  for (let i = 0; i < m; i++) operations[i] = [scanInt(), scanInt()];

  operations.sort((opA, opB) => opB[1] - opA[1]);

  let index = 0;

  for (let i = 0; i < m; i++) {
    const [b, c] = operations[i];
    let stop = false;

    for (let k = 0; k < b; k++) {
      if (a[index] >= c) {
        stop = true;
        break;
      }

      a[index++] = c;

      if (index >= n) {
        stop = true;
        break;
      }
    }

    if (stop) break;
  }

  const digitCount = 16;
  const digitBase = 65536;

  const reducer = (accumulator: number[], currentValue: number) => {
    addDigitArrays(
      createDigitArray(currentValue, digitCount, digitBase),
      accumulator
    );

    return accumulator;
  };

  const sumDigitArray = a.reduce(reducer, createDigitArray(0, digitCount));
  fixDigitArray(sumDigitArray, digitBase);

  log(digitArrayToString(sumDigitArray));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


import sys

def A():
  n = int(sys.stdin.readline().rstrip())
  charge = (n+999)//1000 * 1000 - n
  print(charge)

from collections import Counter
def B():
  n, *s = sys.stdin.read().split()
  c = Counter(s)
  for v in 'AC, WA, TLE, RE'.split(', '):
    print(f'{v} x {c[v]}')

def C():
  h, w, k = map(int, sys.stdin.readline().split())
  c = [sys.stdin.readline().rstrip() for _ in range(h)]
  tot = 0
  for i in range(1<<h):
    for j in range(1<<w):
      cnt = 0
      for y in range(h):
        for x in range(w):
          if i>>y & 1 or j>>x & 1:
            continue
          cnt += c[y][x] ==  '#'
      tot += cnt == k
  print(tot)

def D():
  n, *a = map(int, sys.stdin.read().split())
  a.sort(reverse=True)
  res = a[0] + sum(a[1:1+(n-2)//2])*2 + a[1+(n-2)//2]*(n & 1)
  print(res)

def E():
  pass

def F():
  pass

if __name__ == "__main__":
  # A()
  # B()
  # C()
  D()
  E()
  F()


n = int(input())
A = list(map(int, input().split()))
A.sort(reverse=True)
ans = A[0]
if n%2 == 0:
    ans += sum(A[1:n//2])*2
else:
    ans += sum(A[1:n//2])*2 + A[n//2]

print(ans)


N = int(input())
A = list(map(int, input().split()))

A.sort(reverse=True)
print(A[0] + sum(A[1:(N - 2) // 2 + 1]) * 2 + A[(N - 2) // 2 + 1] * (N % 2))


n = int(input())
a = sorted(map(int, input().split()), reverse=True)

ans, que = 0, [a[0]]
for i in enumerate(a[1:]):
    ans += que[i]
    que += [i, i]
print(ans)


n = int(input())

a = list(map(int, input().split()))
a.sort(reverse=True)

ans = a[0]

cnt = 1
i = 1
while cnt < n-1:
    cnt += 2
    ans += a[i] * 2
    i += 1

if cnt == n:
    ans -= a[i]

print(ans)


n = int(input())
p = list(map(int, input().split()))
p.sort()
s = sum(p)
s -= p[0]
print(s)