#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using P = pair<ll, ll>;

constexpr char newl = '\n';

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

    int n, m;
    cin >> n >> m;

    vector<ll> w(n);
    for (int i = 0; i < n; i++) {
        cin >> w[i];
    }

    vector<P> vl(m);
    for (int i = 0; i < m; i++) {
        cin >> vl[i].second >> vl[i].first;
        vl[i].second = -vl[i].second;
    }
    sort(vl.begin(), vl.end());

    {
        ll maxw = 0;
        for (int i = 0; i < n; i++) {
            maxw = max(maxw, w[i]);
        }
        if (maxw > vl[0].first) {
            cout << -1 << newl;
            return 0;
        }
    }

    map<ll, ll> memo;
    {
        ll maxl = 0;
        for (int i = 0; i < m; i++) {
            if (maxl < -vl[i].second) {
                maxl = -vl[i].second;
                memo[vl[i].first] = maxl;
            }
        }
    }

    vector<int> ids(n);
    iota(ids.begin(), ids.end(), 0);

    ll ans = 1e18;
    ll foo = 0;
    do {
        vector<ll> dp(n, 0);
        for (int ii = 0; ii < n; ii++) {
            int i = ids[ii];
            ll wsum = w[i];
            for (int jj = ii + 1; jj < n; jj++) {
                int j = ids[jj];
                wsum += w[j];
                auto it = memo.lower_bound(wsum);
                if (it == memo.begin()) continue;
                dp[jj] = max(dp[jj], dp[ii] + prev(it)->second);
            }
        }
        ans = min(ans, dp.back());
    } while (next_permutation(ids.begin(), ids.end()));
    cout << ans << newl;
    return 0;
}
#include<iostream>
using namespace std;
int l[200005], r[200005];
long long dp[200005][2];
int n, x, c;
const int aa = 1 << 30; 
int main() {
  cin >> n;
  fill(l + 1, l + 1 + n,aa);
  fill(r + 1, r + 1 + n,-aa);
  for (int i = 1; i <= n; i++) {
    cin >> x >> c;
    l[c] = min(l[c], x);
    r[c] = max(r[c], x);
  }
  for (int i = 1, j = 0; i <= n + 1; i++) {
    if (l[i] != aa) {
      dp[i][0] = min(dp[j][0] + abs(r[i] - l[j]), dp[j][1] + abs(r[i] - r[j]));
      dp[i][1] = min(dp[j][0] + abs(l[i] - l[j]), dp[j][1] + abs(l[i] - r[j]));
      dp[i][0] += abs(l[i] - r[i]), dp[i][1] += abs(l[i] - r[i]);
      j = i;
    }
  }
  cout << dp[n + 1][0];
  return 0;
}