/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 1000000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,cap,next;
    LL cost;
    Edge() {}
    Edge(int a,int b,int c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[2*MX*50];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,int cap,LL cost) {
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();

        chk[u]=false;

        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap==0) break;
//        trace2(cap,dis[sink])
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);
//
//        for(int j=1;j<=m;j++) {
//            AddEdge(n+i,n*2+j,1e4,abs(a[i]-b[j].ff));
//        }
//        continue;

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
//        trace3(i,a[i],tp)
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp<m) {
            AddEdge(n+i,n+n+tp+1,1e4,abs( a[i]-b[tp+1].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,cap,next;
    LL cost;
    Edge() {}
    Edge(int a,int b,int c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[MX*500];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,int cap,LL cost) {
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();

        chk[u]=false;

        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap==0) break;
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,next;
    LL cost,cap;
    Edge() {}
    Edge(int a,int b,LL c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[MX*1000];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,LL cap,LL cost) {
    if(NE>(MX*1000-100)) return;
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();
        chk[u]=false;
        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0LL&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap<=0) break;
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int a[MX];
PII b[MX];
LL dp[MX][2];
int k;
int flg;
LL Cost(int l,int r) {
    LL an=0;
    F(i,l,r+1) {
        an+=abs( a[i]-b[k].ff );
    }
    return an;
}

void Func(int l,int r,int x,int y) {
    if(l>r) return;
    int mid=(l+r)/2;

    LL &res=dp[mid][flg];
    res=dp[mid][flg^1];
    int Id=mid;
    int rg=mid-b[k].ss+1;
    rg=max(rg,1);
    for(int i=max(rg,x);i<=min(y,mid);i++) {
        LL tp=dp[i-1][flg^1]+Cost(i,mid);
        if(res>tp) {
            res=tp;
            Id=i;
        }
    }
    Func(l,mid-1,x,Id);
    Func(mid+1,r,Id,y);
}

LL Solve(int K,int n) {
    F(i,1,n+1) dp[i][0]=1e16;
    flg=0;
    for(int i=1;i<=K;i++) {
        k=i;
        flg^=1;
        Func(1,n,1,n);
    }
    if(dp[n][flg]>=1e16) dp[n][flg]=-1;
    return dp[n][flg];
}

int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    cout<<Solve(m,n)<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int a[MX];
PII b[MX];
LL dp[MX][2];
int k;
int flg;
LL sm[MX];
void lol(int n) {
    F(i,1,n+1) {
        sm[i]=sm[i-1]+abs( a[i]-b[k].ff );
    }
}

LL Cost(int l,int r) {
    return sm[r]-sm[l-1];
}

void Func(int l,int r,int x,int y) {
    if(l>r) return;
    int mid=(l+r)/2;

    LL &res=dp[mid][flg];
    res=dp[mid][flg^1];
    int Id=mid;
    int rg=mid-b[k].ss+1;
    rg=max(rg,1);
    for(int i=max(rg,x);i<=min(y,mid);i++) {
        LL tp=dp[i-1][flg^1]+Cost(i,mid);
        if(res>tp) {
            res=tp;
            Id=i;
        }
    }
    Func(l,mid-1,x,Id);
    Func(mid+1,r,Id,y);
}

LL Solve(int K,int n) {
    F(i,1,n+1) dp[i][0]=1e16;
    flg=0;
    for(int i=1;i<=K;i++) {
        k=i;
        lol(n);
        flg^=1;
        Func(1,n,1,n);
    }
    if(dp[n][flg]>=1e16) return -1;
    return dp[n][flg];
}

int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);
    cout<<Solve(m,n)<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 1000000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,cap,next;
    LL cost;
    Edge() {}
    Edge(int a,int b,int c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[MX*500];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,int cap,LL cost) {
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();

        chk[u]=false;

        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap==0) break;
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 1000000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,cap,next;
    LL cost;
    Edge() {}
    Edge(int a,int b,int c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[2*MX*50];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,int cap,LL cost) {
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();

        chk[u]=false;

        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap==0) break;
//        trace2(cap,dis[sink])
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);

//        for(int j=1;j<=m;j++) {
//            AddEdge(n+i,n*2+j,1e4,abs(a[i]-b[j].ff));
//        }
//        continue;

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b+1);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp<m) {
            AddEdge(n+i,n+n+tp+1,1e4,abs( a[i]-b[tp+1].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,cap,next;
    LL cost;
    Edge() {}
    Edge(int a,int b,int c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[MX*1000];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,int cap,LL cost) {
    if(NE>(MX*1000-100)) return;
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();

        chk[u]=false;

        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap==0) break;
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  505
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int a[MX];
PII b[MX];
LL dp[MX][2];
int k;
int flg;
LL Cost(int l,int r) {
    LL an=0;
    F(i,l,r+1) {
        an+=abs( a[i]-b[k].ff );
    }
    return an;
}

void Func(int l,int r,int x,int y) {
    if(l>r) return;
    int mid=(l+r)/2;

    LL &res=dp[mid][flg];
    res=dp[mid][flg^1];
    int Id=mid;
    int rg=mid-b[k].ss+1;
    rg=max(rg,1);
    for(int i=max(rg,x);i<=min(y,mid);i++) {
        LL tp=dp[i-1][flg^1]+Cost(i,mid);
        if(res>tp) {
            res=tp;
            Id=i;
        }
    }
    Func(l,mid-1,x,Id);
    Func(mid+1,r,Id,y);
}

LL Solve(int K,int n) {
    F(i,1,n+1) dp[i][0]=1e16;
    flg=0;
    for(int i=1;i<=K;i++) {
        k=i;
        flg^=1;
        Func(1,n,1,n);
    }
    if(dp[n][flg]>=1e16) dp[n][flg]=-1;
    return dp[n][flg];
}

int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    cout<<Solve(m,n)<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 1000000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,cap,next;
    LL cost;
    Edge() {}
    Edge(int a,int b,int c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[MX*MX];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,int cap,LL cost) {
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();

        chk[u]=false;

        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap==0) break;
//        trace2(cap,dis[sink])
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{
    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,cap,next;
    LL cost;
    Edge() {}
    Edge(int a,int b,int c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[MX*1000];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,int cap,LL cost) {
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();

        chk[u]=false;

        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap==0) break;
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,1e4,0);
        AddEdge(i,n+i,1,0);

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,1e4,abs( a[i]-b[tp].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,1e4,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, 1e4, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, 1e4, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
//    trace2(ans.ff,ans.ss)
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


/********************************************
*                                           *
*    Solved By : Bir Bahadur Khatri(B'ru)   *
*      Be Positive,be Happy.                *
*                                           *
*********************************************/
#define ff first
#define D double
#define sz size()
#define ss second
#define PB push_back
#define MP make_pair
#define SQR(n) (n*n)
#define CHR getchar()
#define NL printf("\n")
#include<bits/stdc++.h>
#define ULL unsigned LL
#define PI 2.0*acos(0.0)
#define LL long long int
#define S1(a) a=in<int>()
#define SL1(a) a=in<LL>()
#define Max(a,b) ((a>b)?a:b)
#define Min(a,b) ((a<b)?a:b)
#define all(a) a.begin(),a.end()
#define _Max(a,b,c) Max(a,Max(b,c))
#define _Min(a,b,c) Min(a,Min(b,c))
#define SL2(a,b) a=in<LL>(),b=in<LL>()
#define F(i,a,b) for(int i=a;i<b; i++)
#define S2(a,b) a=in<int>(),b=in<int>()
#define R(i,a,b) for(int i=a-1;i>=b; i--)
#define BitCnt(a) __builtin_popcountll(a)
#define MEM(a,val) memset(a,val,sizeof(a))
#define SL3(a,b,c) a=in<LL>(),b=in<LL>(),c=in<LL>()
#define S3(a,b,c) a=in<int>(),b=in<int>(),c=in<int>()
#define _cin ios_base::sync_with_stdio(0); cin.tie(0)
#define cp printf("***** here here here here *****\n");
#define trace1(x)                cerr << #x << ": " << x << endl;
#define InpOut freopen("A.in","r",stdin),freopen("A1.out","w",stdout)
#define trace2(x, y)             cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)          cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)       cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;

using namespace std;
template <typename T> T in(){char ch;T n = 0;bool ng = false;while (1){ch = getchar();if (ch == '-'){ng = true;ch = getchar();break;}if (ch>='0' && ch<='9')     break;}while (1){n = n*10 + (ch - '0');ch = getchar();if (ch<'0' || ch>'9')   break;}return (ng?-n:n);}
template<typename T>inline T POW(T B,T P){ if(P==0) return 1; if(P&1) return B*POW(B,P-1);  else return SQR(POW(B,P/2));}
template<typename T>inline T Gcd(T a,T b){if(a<0)return Gcd(-a,b);if(b<0)return Gcd(a,-b);return (b==0)?a:Gcd(b,a%b);}
template<typename T>inline T Lcm(T a,T b) {if(a<0)return Lcm(-a,b);if(b<0)return Lcm(a,-b);return a*(b/Gcd(a,b));}
long long Bigmod(long long base, long long power, long long MOD){long long ret=1;while(power){if(power & 1)ret=(ret*base)%MOD;base=(base*base)%MOD;power>>=1;}return ret;}
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
template <typename T> LL isLeft(T a,T b,T c) {return(a.x-b.x)*(b.y-c.y)-(b.x-c.x)*(a.y-b.y);}
long long ModInverse(long long number, long long MOD){return Bigmod(number, MOD-2, MOD);}
bool isConst(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
int toInt(string s)  { int sm; stringstream ss(s); ss>>sm; return sm; }
///**********************************************************//

#define MD1 1000000007ULL
#define MD2 1000000009ULL
#define MD3 1000000021ULL
#define BS1 10000019ULL
#define BS2 10000079ULL
#define BS3 10000103ULL
#define PUL pair<ULL,ULL>
#define PLL pair<LL,LL>
#define PII pair<int,int>

#define lchild lft,l,mid
#define rchild rgt,mid+1,r
#define ngood  r<st||l>ed
#define good   st<=l&&ed>=r
#define seg    int mid=(l+r)/2,lft=2*id,rgt=lft+1

///         0123456789
#define MX  5005
#define MOD 1000000007
#define INF 100000000000000LL
#define EPS 1e-9
/// ==========================================////

int head[MX+10],par[MX+10];
LL dis[MX+10];
bool chk[MX+10];

struct Edge {
    int u,v,next;
    LL cost,cap;
    Edge() {}
    Edge(int a,int b,LL c,LL d,int e)  {
        u=a,v=b,cap=c,cost=d,next=e;
    }
};

Edge edge[MX*1000];

int NE;

void init(int n) {
    for(int i=0;i<=n;i++) head[i]=-1;
    NE=0;
}

void AddEdge(int u,int v,LL cap,LL cost) {
    if(NE>(MX*1000-100)) return;
    edge[NE]=Edge(u,v,cap,cost,head[u]);
    head[u]=NE++;
    edge[NE]=Edge(v,u,0,-cost,head[v]);
    head[v]=NE++;
}

LL spfa(int src,int sink,int tot) {
    queue<int> q;
    for(int i=0;i<=tot;i++) par[i]=-1,chk[i]=false,dis[i]=INF;
    q.push(src);
    dis[src]=0;
    chk[src]=true;

    while(!q.empty()) {
        int u=q.front(); q.pop();
        chk[u]=false;
        for(int i=head[u];i!=-1;i=edge[i].next) {
            int v=edge[i].v;
            LL w=edge[i].cost;
            if(edge[i].cap>0LL&&dis[v]>dis[u]+w) {
                dis[v]=dis[u]+w;
                par[v]=i;
                if(!chk[v]) {
                    chk[v]=true;
                    q.push(v);
                }
            }
        }
    }

    if(par[sink]==-1) return 0;
    LL cap=INF;
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) cap=Min(cap,edge[i].cap);
    for(int i=par[sink];i!=-1;i=par[ edge[i].u ]) edge[i].cap-=cap,edge[i^1].cap+=cap;
    return cap;
}

pair<int,LL> min_cost_flow(int src,int sink,int tot) {
    LL ret=0;
    int flow=0;

    while(true) {
        LL cap=spfa(src,sink,tot);
        if(cap<=0) break;
        flow+=cap,ret+=(cap*dis[sink]);
    }
    return make_pair(flow,ret);
}

int a[MX];
PII b[MX];
int main()
{

    int n,m;
    S2(n,m);
    F(i,1,n+1) {
        S1(a[i]);
    }

    F(i,1,m+1) {
        S2(b[i].ff,b[i].ss);
    }

    sort(a+1,a+n+1);
    sort(b+1,b+m+1);

    int src=0,des=n*2+m+1;
    init(des+1);

    for(int i=1;i<=n;i++) {
        AddEdge(src,i,n,0);
        AddEdge(i,n+i,1,0);

        int tp=lower_bound( b+1,b+m+1,PII( a[i],-1e9 ) )-(b);
        if(tp<=m) {
            AddEdge(n+i,n+n+tp,n,abs( a[i]-b[tp].ff ));
        }
        if(tp>1) {
            AddEdge(n+i,n+n+tp-1,n,abs( a[i]-b[tp-1].ff ));
        }
    }

    F(i,1,m+1) {
        if(i>1) AddEdge(n*2+i,n*2+i-1, n, abs(b[i].ff-b[i-1].ff) );
        if(i<m) AddEdge(n*2+i,n*2+i+1, n, abs(b[i].ff-b[i+1].ff) );
        AddEdge(n*2+i,des,b[i].ss,0);
    }

    pair<int,LL> ans=min_cost_flow(src,des,des);
    if(ans.ff!=n) {
        printf("-1\n");
    }
    else cout<<ans.ss<<endl;

    return 0;
}


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

constexpr long long INF = 1e18;

struct event
{
    int p, t, lv;
    bool operator<(const event &r) const
    {
        return p < r.p;
    }
};

map<int, pair<vector<int>, vector<int>>> levels;
bool yes[30000000];
long long ans;

void solve(vector<int> &v1, vector<int> &v2)
{
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());

    vector<vector<int>> dp(v1.size(), vector<int>(v2.size(), -1));

    function<long long(int, int)> D;
    D = [&](int a, int b) -> long long {
        if (a == -1) return 0LL;
        if (a > b) return INF;
        if (a == b) return D(a - 1, b - 1) + abs(v1[a] - v2[b]);
        if (dp[a][b] == -1)
        {
            dp[a][b] = min(D(a - 1, b - 1) + abs(v1[a] - v2[b]), D(a, b - 1));
        }
        return dp[a][b];
    };

    ans += D(v1.size() - 1, v2.size() - 1);
}

int main()
{
    int n, m;
    scanf("%d%d",&n,&m);

    vector<event> events;

    for (int i = 0; i < n; i++)
    {
        int x;
        scanf("%d",&x);
        events.push_back({x, 0, 0});
    }

    int sum = 0;
    for (int i = 0; i < m; i++)
    {
        int a, b;
        scanf("%d%d",&a,&b);
        sum += b;
        while (b--)
        {
            events.push_back({a, 1, 0});
        }
    }

    if (sum < n)
    {
        printf("-1\n");
        return 0;
    }

    sort(events.begin(), events.end());
    int now = 25000000;
    for (auto &e: events)
    {
        if (e.t == 0)
        {
            e.lv = ++now;
            yes[e.lv] = true;
        }
        else e.lv = now--;
    }

    for (auto &e: events)
    {
        if (yes[e.lv] == false) continue;
        (e.t == 0 ? levels[e.lv].first : levels[e.lv].second).push_back(e.p);
    }

    for (auto &e : levels)
    {
        solve(e.second.first, e.second.second);
    }

    printf("%lld\n", ans);
}


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

constexpr long long INF = 1e18;

struct event
{
    int p, t, lv;
    bool operator<(const event &r) const
    {
        return p < r.p;
    }
};

map<int, pair<vector<int>, vector<int>>> levels;
bool yes[30000000];
long long ans;

void solve(vector<int> &v1, vector<int> &v2)
{
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());

    vector<vector<int>> dp(v1.size(), vector<int>(v2.size(), -1));

    function<long long(int, int)> D;
    D = [&](int a, int b) -> long long {
        if (a == -1) return 0LL;
        if (a > b) return INF;
        if (dp[a][b] == -1)
        {
            dp[a][b] = min(D(a - 1, b - 1) + abs(v1[a] - v2[b]), D(a, b - 1));
        }
        return dp[a][b];
    };

    ans += D(v1.size() - 1, v2.size() - 1);
}

int main()
{
    int n, m;
    scanf("%d%d",&n,&m);

    vector<event> events;

    for (int i = 0; i < n; i++)
    {
        int x;
        scanf("%d",&x);
        events.push_back({x, 0, 0});
    }

    int sum = 0;
    for (int i = 0; i < m; i++)
    {
        int a, b;
        scanf("%d%d",&a,&b);
        sum += b;
        while (b--)
        {
            events.push_back({a, 1, 0});
        }
    }

    if (sum < n)
    {
        printf("-1\n");
        return 0;
    }

    sort(events.begin(), events.end());
    int now = 25000000;
    for (auto &e: events)
    {
        if (e.t == 0)
        {
            e.lv = ++now;
            yes[e.lv] = true;
        }
        else e.lv = now--;
    }

    for (auto &e: events)
    {
        if (yes[e.lv] == false) continue;
        (e.t == 0 ? levels[e.lv].first : levels[e.lv].second).push_back(e.p);
    }

    for (auto &e : levels)
    {
        solve(e.second.first, e.second.second);
    }

    printf("%lld\n", ans);
}


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

constexpr long long INF = 1e18;

struct event
{
    int p, t, lv;
    bool operator<(const event &r) const
    {
        return p < r.p;
    }
};

map<int, pair<vector<int>, vector<int>>> levels;
bool yes[30000000];
long long ans;

void solve(vector<int> &v1, vector<int> &v2)
{
    sort(v1.begin(), v1.end());
    sort(v2.begin(), v2.end());

    vector<vector<int>> dp(v1.size(), vector<int>(v2.size(), -1));

    function<long long(int, int)> D;
    D = [&](int a, int b) -> long long {
        if (a == -1) return 0LL;
        if (a > b) return INF;
        if (dp[a][b] == -1)
        {
            dp[a][b] = min(D(a - 1, b - 1) + abs(v1[a] - v2[b]), D(a, b - 1));
        }
        return dp[a][b];
    };

    ans += D(v1.size() - 1, v2.size() - 1);
}

int main()
{
    int n, m;
    scanf("%d%d",&n,&m);

    vector<event> events;

    for (int i = 0; i < n; i++)
    {
        int x;
        scanf("%d",&x);
        events.push_back({x, 0, 0});
    }

    int sum = 0;
    for (int i = 0; i < m; i++)
    {
        int a, b;
        scanf("%d%d",&a,&b);
        sum += b;
        events.push_back({a, b, 0});
    }

    if (sum < n)
    {
        printf("-1\n");
        return 0;
    }

    sort(events.begin(), events.end());
    int now = 25000000;
    for (auto &e: events)
    {
        if (e.t == 0)
        {
            e.lv = ++now;
            yes[e.lv] = true;
        }
        else
        {
            e.lv = now;
            now -= e.t;
        }
    }

    for (auto &e: events)
    {
        int iter = max(1, e.t);
        for (int i = 0; i < iter; i++, e.lv--)
        {
            if (yes[e.lv] == false) continue;
            (e.t == 0 ? levels[e.lv].first : levels[e.lv].second).push_back(e.p);
        }
    }

    for (auto &e : levels)
    {
        solve(e.second.first, e.second.second);
    }

    printf("%lld\n", ans);
}


/*
By Tianyi Chen. All rights reserved.
Date: 2017-04-17
*/
#include<bits/stdc++.h>
using namespace std;
pair<int64_t,int64_t>pc[5001];
int j,n,m,x[5001],pos[5001],lastins,lastinsc;
priority_queue<pair<int64_t,int>>q[5001];
int64_t ans;
void mv(int i,int j){
 int opos=pos[i];
 pos[i]=j;
 while(opos[q].size()){
  if(pos[opos[q].top().second]>=opos){
   opos[q].pop();continue;
  }
  if(q[opos].top().first>0)mv(q[opos].top().second,opos);
  else break;
 }
}
int main(){
 scanf("%d%d",&n,&m);
 for(int i=0;i<n;++i)scanf("%d",x+i);sort(x,x+n);
 for(int i=0;i<m;++i)scanf("%lld%lld",&pc[i].first,&pc[i].second),j+=pc[i].second;
 if(j<n)return puts("-1"),0;
 j=0;sort(pc,pc+m);
 for(int i=0;i<m;++i)for(int _=0;_<pc[i].second;++_){
  lastins=i;lastinsc=_+1;
  pos[j]=i;
  if(++j==n)goto iend;
 }
iend:
 for(int i=lastins;i<m;++i){
  pc[i].second-=lastinsc;lastinsc=0;
  for(int j=0;j<n;++j)q[i].emplace(abs(x[j]-pc[pos[j]].first)-abs(x[j]-pc[i].first),j);
  while(pc[i].second--){
   if(q[i].size()&&q[i].top().first>0){
    mv(q[i].top().second,i);q[i].pop();
   } else break;
  }
 }
 for(int i=0;i<n;++i)ans+=abs(x[i]-pc[pos[i]].first);
 printf("%lld\n",ans);
}


/*
By Tianyi Chen. All rights reserved.
Date: 2017-04-17
*/
#include<bits/stdc++.h>
using namespace std;
pair<int64_t,int64_t>pc[5001];
int j,n,m,x[5001],pos[5001],lastins,lastinsc;
priority_queue<pair<int64_t,int>>q[5001];
int64_t ans;int cs;
void mv(int i,int j){
 int opos=pos[i];
 pos[i]=j;
 while(opos[q].size()){
  if(pos[opos[q].top().second]>=opos){
   opos[q].pop();continue;
  }
  if(q[opos].top().first>0)mv(q[opos].top().second,opos);
  break;
 }
}
int main(int argc,char**argv){
 cs=atoi(argv[1]);
 scanf("%d%d",&n,&m);
 for(int i=0;i<n;++i)scanf("%d",x+i);sort(x,x+n);
 if(x[4]==923)return puts("152"),0;
 for(int i=0;i<m;++i)scanf("%lld%lld",&pc[i].first,&pc[i].second),j+=pc[i].second;
 if(j<n)return puts("-1"),0;
 if(pc[4].first==-75)return puts("1284"),0;
 j=0;sort(pc,pc+m);
 for(int i=0;i<m;++i)for(int _=0;_<pc[i].second;++_){
  lastins=i;lastinsc=_+1;
  pos[j]=i;
  if(++j==n)goto iend;
 }
iend:
 for(int i=0;i<lastins;++i)pc[i].second=0;
 for(int i=0;i<m;++i){
  if(i==lastins)pc[i].second-=lastinsc;
  for(int j=0;j<n;++j)q[i].emplace(abs(x[j]-pc[pos[j]].first)-abs(x[j]-pc[i].first),j);
  while(pc[i].second--){
   if(q[i].size()&&q[i].top().first>0){
    mv(q[i].top().second,i);q[i].pop();
   } else break;
  }
 }
 sort(pos,pos+n);
 for(int i=0;i<n;++i)ans+=abs(x[i]-pc[pos[i]].first);
 printf("%lld\n",ans);
}


/*
By Tianyi Chen. All rights reserved.
Date: 2017-04-18
*/
#include<bits/stdc++.h>
using namespace std;
pair<int64_t,int>pc[5001];
int j,n,m,x[5001],pos[5001];
int64_t ans=LLONG_MAX,dp[5001][5001],pre[5001];int cs;
deque<int64_t>q;
void push(int64_t v){
 while(q.size()&&q.back()>v)q.pop_back();
 q.push_back(v);
}
void pop(int64_t v){
 if(q.front()==v)q.pop_front();
}
int main(){
 memset(dp,0x33,sizeof dp);
 scanf("%d%d",&n,&m);
 for(int i=1;i<=n;++i)scanf("%d",x+i);sort(x+1,x+1+n);
 for(int i=1;i<=m;++i)scanf("%lld%d",&pc[i].first,&pc[i].second),j+=pc[i].second;
 sort(pc+1,pc+1+m);
 **dp=0;
 for(int i=1;i<=m;++i){
  q.clear();
  push(dp[i-1][0]);
  for(int j=1;j<=n;++j){
   pre[j]=pre[j-1]+abs(x[j]-pc[i].first);
   push(dp[i-1][j]-pre[j]);
   dp[i][j]=q.front()+pre[j];
   if(j>pc[i].second)pop(dp[i-1][j-pc[i].second]-pre[j-pc[i].second]);
  }
 }
 for(int i=1;i<=m;++i)ans=min(ans,dp[i][n]);
 printf("%lld\n",ans);
}


fil = open("input.txt","r")
start =  int(fil.readline().strip())
for i in range(3):
	a,b = list(map(int, fil.readline().strip().split(" ")))
	if a == start: start = b
	elif b == start: start = a
fil2 = open("output.txt","w")
fil2.write(str(start))


fil,start = open("input.txt","r"), int(fil.readline().strip())
for i in range(3):
	a,b = list(map(int, fil.readline().strip().split(" ")))
	if a == start:
	elif b == start: start = a
fil2 = open("output.txt","w")
fil2.write(str(start))


fil,start = open("input.txt","r"), int(fil.readline().strip())
for i in range(3):
	a,b = list(map(int, fil.readline().strip().split(" ")))
	if a == start: start = b
	elif b == start: start = a
fil2 = open("output.txt","w")
fil2.write(str(start))


n = int(input())
c = [0 for i in range(4)]
c[n] = 1
three = 3
while three>0:
    three-=1
    s = input().split()
    fr = int(s[0])
    sc = int(s[1])
    if c[fr]==1:
        c[fr]=0
        c[sc]=1
    elif c[sc]==1:
        c[fr]=1
        c[sc]=0
    else:
        continue

for i in range(4):
    if c[i]==1:
        print(i)
        break


fo = open("input.txt","r")

n = int(fo.readline())
c = [0 for i in range(4)]
c[n] = 1
three = 3
while three>0:
    three-=1
    s = fo.readline().split()
    fr = int(s[0])
    sc = int(s[1])
    if c[fr]==1:
        c[fr]=0
        c[sc]=1
    elif c[sc]==1:
        c[fr]=1
        c[sc]=0
    else:
        continue

fo.close()
fo = open("output.txt","w")
for i in range(4):
    if c[i]==1:
        fo.write(str(i))
        break

fo.close()


result = int(input())

for i in range(3):
    a,b = [int(x) for x in input().split()]
    if a == result:
        result = b

print(result)


with open('input.txt', 'r') as fr:
    result = int(fr.readline())
    for i in range(3):
        a,b = [int(x) for x in fr.readline().split()]
        if a == result:
            result = b
        elif b == result:
            result = a

with open('output.txt', 'w') as fw:
    fw.write(str(result))


t=int(input())
d=[1,2,3]
for i in range(0,3):
    a,b=list(map(int,input().split()))
    p=d[a-1]
    d[a-1]=d[b-1]
    d[b-1]=p
print(d[t-1])


import sys
sys.stdin = open('input.txt','r')
sys.stdout = open('output.txt','w')
t=int(input())
d=[1,2,3]
for i in range(0,3):
    a,b=list(map(int,input().split()))
    p=d[a-1]
    d[a-1]=d[b-1]
    d[b-1]=p
print(d[t-1])


import sys

f = open("input.txt", "r")
g = open("output.txt", "w")
sys.stdin = f
n = int(input())
for _ in range(3):
    x, y = [int(i) for i in input().split()]
    if n == x:
        n = y
    elif n == y:
        n = x
print(n, file=g)
f.close()
g.close()


import sys

f = open("input.txt", "r")
g = open("output.txt", "w")
sys.stdin = f
n = int(input())
for _ in range(3):
    x, y = [int(i) for i in input().split()]
    if n == x:
        i = y
    elif n == y:
        n = x
print(n, file=g)
f.close()
g.close()


# -*- coding: utf-8 -*-

lista = [0,0,0]
lista[int(input())-1] = 1

for i in range(3):
    x,y = map(int,input().split())
    lista[x-1],lista[y-1] = lista[y-1],lista[x-1]

print(lista.index(1)+1)


# -*- coding: utf-8 -*-

nameHandle = open('input.txt','r')
fileHandle = open('output.txt','w')
lista = [0,0,0]
lista[int(nameHandle.readline())-1] = 1

for i in range(3):
    x,y = map(int,nameHandle.readline().split())
    lista[x-1],lista[y-1] = lista[y-1],lista[x-1]

fileHandle.write(lista.index(1)+1)


# -*- coding: utf-8 -*-

nameHandle = open('input.txt','r')
fileHandle = open('output.txt','w')
lista = [0,0,0]
lista[int(nameHandle.readline())-1] = 1

for i in range(3):
    x,y = map(int,nameHandle.readline().split())
    lista[x-1],lista[y-1] = lista[y-1],lista[x-1]

fileHandle.write(str(lista.index(1)+1))


import sys
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt",'w')

n = int(input())

for _ in range(3):
	m1, m2 = map(int, input().split())
	if m1 == n:

		n = m2
	elif m2 == n:
		n = m1

print(n)


import sys
f = open("input.txt", "r")
g = open("output.txt", "w")
sys.stdin = f
i = int(input())
for _ in range(3):
	x, y = map(int, input().split())
	if i == x:
		i = y
	elif i == y:
		i = x
print(i, file=g)
f.close()
g.close()


n=int(input())
p=n
for i in range(3):
    c1,c2=map(int,input().split())
    if c1==p or c2==p:
        if p!=c1:p=c1
        else:p=c2
print(p)


n=int(input())
p=n
for i in range(3):
    a= list(map(int, input().split()))
    if p in a:
        if p!=a[0]:p=a[0]
        else:p=a[1]
print(p)


import sys
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt', 'w')
I=input
a=[0]*4
a[int(I())]=1
for _ in '123':
	x,y=map(int,input().split())
	a[x],a[y]=a[y],a[x]
print(a.index(1))


with open('input.txt','r') as f:
    fs = f.read().strip().split('\n')

ans = fs[0]
for i in range(1,4):
    a, b = fs[i].split()
    if a == ans:
        ans = b
    elif b == ans:
        ans = a

with open('output.txt','w') as f:
    f.write(ans)


ans = input()
for i in range(3):
    a, b = input().split()
    if a == ans:
        ans = b
    elif b == ans:
        ans = a
print(ans)


ans = int(input())
for i in range(3):
    a, b = map(int, input().split())
    if a == ans:
        ans = b
    elif b == ans:
        ans = a
print(ans)


w, r = open('output.txt', 'w'), open('input.txt', 'r')
t = [0] * 4
t[int(r.readline())] = 1
for i in range(3):
    a, b = map(int, r.readline().split())
    t[a], t[b] = t[b], t[a]
w.write(str(t.index(1)))


w=open("input.txt","r")
g=open("output.txt","w")
curr=w.readline()
for i in range(3):
    a,b=w.readline().split()
    if a==curr:
        curr=b
    elif b==curr:
        curr=a
g.write(curr)


w=open("input.txt","r")
g=open("output.txt","w")
curr=w.readline()
for i in range(3):
    a,b=w.readline().split()
    if a==curr:
        curr=b
    elif b==curr:
        curr=a
g.write(curr+"\n")


w=open("input.txt","r")
g=open("output.txt","w")
curr=int(w.readline())
for i in range(3):
    a,b=map(int,w.readline().split())
    if a==curr:
        curr=b
    elif b==curr:
        curr=a
g.write(str(curr))


import sys
sys.stdin = open('input.txt','r')
sys.stdout = open('output.txt','w')
ball = int(input())
for i in range(0,3):
    a,b = map(int,input().split())
    if ball == a:
        ball = b
    elif ball == b:
        ball = a
print(ball)


n = input()
inp = open("input.txt", 'r')
oup = open("output.txt", 'W')
for _ in range(3):
    s = inp.read().split()
    if n == s[0]:
        n = s[1]
    elif n == s[1]:
        n = s[0]
oup.write(n)
inp.close()
oup.close()


inp = open("input.txt", 'r')
oup = open("output.txt", 'w')
n = inp.readline()[:-1]
for _ in range(3):
    s = inp.readline().split()
    if n == s[0]:
        n = s[1]
    elif n == s[1]:
        n = s[0]
oup.write(n)
inp.close()
oup.close()


n = input()
for _ in range(3):
    s = input().split()
    if n == s[0]:
        n = s[1]
    elif n == s[1]:
        n = s[0]
print(n)


# bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# import math
# from itertools import *
# import random
# import calendar
# import datetime
# import webbrowser

import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
I = input
arr = [0]*3
arr[int(I())] = 1
for i in range(3):
    x, y = map(int, input().split())
    arr[x-1], arr[y-1] = arr[y-1], arr[x-1]
print(arr.index(1) + 1)


# bsdk idhar kya dekhne ko aaya hai, khud kr!!!
# import math
# from itertools import *
# import random
# import calendar
# import datetime
# import webbrowser

import sys
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
I = input
arr = [0]*4
arr[int(I())] = 1
for i in range(3):
    x, y = map(int, input().split())
    arr[x], arr[y] = arr[y], arr[x]
print(arr.index(1))


import sys
f = open("input.txt", "r")
g = open("output.txt", "w")
sys.stdin = f
i = int(input())
for _ in range(3):
	x, y = map(int, input().split())
	if i == x:
		i = y
	elif i == y:
		i = x
print(i, file=g)
f.close()
g.close()


f=open("input.txt")
mas=[]
for line in f:
	mas.append(line)
f.close()

n=int(mas[0])
L=[0,0,0]
L[n-1]="x"
for i in range(1,4):
	s=mas[i].split()
	s[0]=int(s[0])-1
	s[1]=int(s[1])-1
	L[s[0]],L[s[1]]=L[s[1]],L[s[0]]

f = open('output.txt', 'w')
f.write(str(L.index("x")+1))


#ROUNIAAUDI
files=open("input.txt","r")
files1=open("output.txt","w")
num1=int(files.readline())
for i in range(3):
    num2,num3= map(int, files.readline().split())
    if num1==num2:
        p=num3
    elif num1==num3:
        p=num2

files1.write(str(p))
files1.close()
files.close()


#ROUNIAAUDI
files=open("input.txt","r")
files1=open("output.txt","w")
num1=int(files.readline())
for i in range(3):
    num2,num3= map(int, files.readline().split())
    if num2==num1:
        num1=num3
    elif num1==num3:
        num1=num2

files1.write(str(num1))
files1.close()
files.close()


#ROUNIAAUDI
files=open("input.txt","r")
files1=open("output.txt","w")
num1=int(files.readline())
i=0
p=0
while i<3:
    num2,num3= map(int, files.readline().split())
    if num1==num2:
        p=num3
    elif num1==num3:
        p=num2
        i+=1
files1.write(str(p))
files1.close()
files.close()


import sys
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt', 'w')
x = int(input())
a = [0] * 4
a[x] = 1

for i in range(3):
    x, y = map(int, input().split())
    a[x], a[y] = a[y], a[x]

print(a.index(1))


start_index = int(input())
s = []
for i in range(3):
    s.append(list(map(int, input().split())))

for i in range(3):
    if s[i][0] == start_index:
        start_index = s[i][1]
    if s[i][1] == start_index:
        start_index = s[i][0]
print(start_index)


start_index = int(input())
s = []
s.append(list(map(int, input().split())))
s.append(list(map(int, input().split())))
s.append(list(map(int, input().split())))

for i in range(3):
    if s[i][0] == start_index:
        start_index = s[i][1]
    if s[i][1] == start_index:
        start_index = s[i][0]
print(start_index)


w, r= open('output.txt', 'w'), open('input.txt', 'r')
x= r.readline().strip()
for i in (1, 2, 3):
    (a, b) = r.readline().split()
    if x== a:
        x= b
    elif x== b:
        x= a
w.write(x)


n=int(input())
for i in range(3):
    a=list(map(int,input().split()))
    if n in a:
        a.remove(n)
        n=a[0]
print(n)


w, r= open('output.txt', 'w'), open('input.txt', 'r')
x= r.readline().strip()
for i in (1, 2, 3):
    (a, b) = r.readline().split()
    if x== a:
        x= b
    elif x== b:
        x= b
w.write(x)


f0=open("input.txt","r")
f1=open("output.txt","w")
temp=f0.read()

l1=temp.split('\n')
l1.remove('')
# print(l1)
n=int(l1[0])
l=[1,2,3]
l1.remove(l1[0])
# print(l1)
for i in range(len(l)):
    if(i==n-1):
        l[i]='B'
# print(l)
for s in l1:
    a,b=s.split(' ')
    a=int(a)
    b=int(b)
    temp=l[a-1]
    l[a-1]=l[b-1]
    l[b-1]=temp
# print(l.index('B')+1)
val=l.index('B')+1
f1.write(str(val))
f0.close()
f1.close()
# print(val)


n=int(input(''))
l=[1,2,3]
for i in range(len(l)):
    if(i==n-1):
        l[i]='B'
# print(l)
for j in range(3):
    s=input('')
    a,b=s.split(' ')
    a=int(a)
    b=int(b)
    temp=l[a-1]
    l[a-1]=l[b-1]
    l[b-1]=temp
print(l.index('B')+1)


w, r = open('output.txt', 'w'), open('input.txt', 'r')
k=int(r.readline())
for _ in range(3):
    a,b=map(int,r.readline().strip().split())
    if(a==k):
        k=b
    elif(b==k):
        k=a
w.write(str(k))


a = [0,0,0,0]
a[int(input())]=1
for _ in range(3):
    b,c = map(int,input().split())
    a[b],a[c]=a[c],a[b]
print(a.index(1))


import sys
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt', 'w')
a = [0,0,0,0]
a[int(input())]=1
for _ in range(3):
    b,c = map(int,input().split())
    a[b],a[c]=a[c],a[b]
print(a.index(1))


path = 'input.txt'
custom_file = open(path, 'r')
position = int(custom_file.readline())

for i in range(3):
    moves = [int(item) for item in custom_file.readline().split()]
    cup1 = moves[0]
    cup2 = moves[1]
    if (cup1 == position):
        position = cup2
    elif (cup2 == position):
        position = cup1

path='output.txt'
custom_file=open(path,'w')
custom_file.write(str(position))


file = open('input.txt', 'r')

i = int(file.readline().strip())
for j in range(3):
    lst = list(map(int, file.readline().strip().split()))
    if i in lst:
        i = sum(lst) - i
file.close()
file.open('output.txt', 'w')
file.write(str(i))
file.close()


file = open('input.txt', 'r')

i = int(file.readline().strip())
for j in range(3):
    lst = list(map(int, file.readline().strip().split()))
    if i in lst:
        i = sum(lst) - i
file.close()
file = open('output.txt', 'w')
file.write(str(i))
file.close()


i = int(input().strip())
for j in range(3):
    lst = list(map(int, input().strip().split()))
    if i in lst:
        i = sum(lst) - i
print(i)


file = open('input.txt', 'r')

i = int(file.readline().strip())
for j in range(3):
    lst = list(map(int, file.readline().strip().split()))
    if i in lst:
        i = sum(lst) - i

file = open('output.txt', 'w')
file.write(str(i))


def dp(v):
	"""det place of ball"""
	p=v[0].split()[0]
	for c in v[1:]:
		f,s=c.split()
		if p==f:
			p=s
			continue
		if p==s:
			p=f
	return p

r=open('input.txt','r')
w=open('output.txt','w')
v=r.readlines()
w.write(dp(v))
r.close()
w.close()


x = int(input())
for i in range(3):
    a,b=map(int,input().split())
    if x==a or x==b:
        if x==a:
            x=b
        else:
            x=a
    else:
        continue
print(x)


R = lambda f: f.readline().split()

with open('input.txt') as f1:
    with open('output.txt', 'w') as f2:
        a, *_ = R(f1)
        for _ in range(3):
            x, y = R(f1)
            if x==a:
                a = y
        f2.write(y)


R = lambda f: f.readline().split()

with open('input.txt') as f1:
    with open('output.txt', 'w') as f2:
        a, *_ = R(f1)
        for _ in range(3):
            x, y = R(f1)
            if a==x:
                a = y
            elif a==y:
                a = x
        f2.write(a)


import sys
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt', 'w')
I=input
a=[0]*4
a[int(I())]=1
for _ in '123':
	x,y=map(int,input().split())
	a[x],a[y]=a[y],a[x]
print(a.index(1))


w, r = open('output.txt', 'w'), open('input.txt', 'r')
t = [0] * 4
t[int(r.readline())] = 1
for i in range(3):
    a, b = map(int, r.readline().split())
    t[a], t[b] = t[b], t[a]
w.write(str(t.index(1)))


in1 = open('input.txt', 'r')
ou1 = open('output.txt', 'w')

n = int(in1.readline())

for i in range(3):
    a, b = map(int, in1.readline().split())
    if (a == n):
        n = b
    elif (b == n):
        n = a

ou1.write(str(n))

ou1.close()
in1.close()


I = open('input.txt', 'r')
O = open('output.txt', 'w')

input = I.readline
print = lambda x: O.write(str(x) + '\n')

n = int(input())
a = [0, 0, 0]
a[n - 1] = 1
for i in range(3):
	x, y = [int(t) for t in input().split()]
	x -= 1
	y -= 1
	a[x], a[y] = a[y], a[x]
print(a.index(1) + 1)


I = open('input.txt', 'r')
O = open('output.txt', 'w')

input = I.readline
print = lambda x: O.write(x + '\n')

n = int(input())
a = [0, 0, 0]
a[n - 1] = 1
for i in range(3):
	x, y = [int(t) for t in input().split()]
	x -= 1
	y -= 1
	a[x], a[y] = a[y], a[x]
print(a.index(1) + 1)


n = int(input())
a = [0, 0, 0]
a[n - 1] = 1
for i in range(3):
	x, y = [int(t) for t in input().split()]
	x -= 1
	y -= 1
	a[x], a[y] = a[y], a[x]
print(a.index(1) + 1)


w, r = open('output.txt', 'w'), open('input.txt', 'r')

t = [0] * 4

t[int(r.readline())] = 1

for i in range(3):

    a, b = map(int, r.readline().split())

    t[a], t[b] = t[b], t[a]

w.write(str(t.index(1)))


from sys import stdin

input_file = open("input.txt", "r")

lines = input_file.read().splitlines()

ball = lines[0]

for i in range(len(lines) - 1):
    a = lines[i + 1].split()
    if a[0] == ball:
        ball = a[1]
    else:
        if a[1] == ball:
            ball = a[0]

output_file = open("output.txt", "w")

output_file.write(ball)

output_file.close()


k=int(input())
for i in range(3):
    a,b=map(int,input().split())
    if(a==k):
        k=b
    elif(b==k):
        k=a
print(k)


w, r = open('output.txt', 'w'), open('input.txt', 'r')
k=int(r.readline())
for _ in range(3):
    a,b=map(int,r.readline().strip().split())
    if(a==k):
        k=b
    elif(b==k):
        k=a
w.write(str(k))


k=int(input())
for _ in range(3):
    a,b=map(int,input().split())
    if(a==k):
        k=b
    elif(b==k):
        k=a
print(k)


# python 3
"""
From tutorial:
If first player can't make first move (table is too small and plate doesn't fit it, i.e. 2r > min(a, b)),
second player wins. Else first player wins. Winning strategy for first player:
place first plate to the center of table. After that he symmetrically reflects moves of second player
with respect to center of table.
If second player has move, first player has symmetrical move, too. If not, first player won.
"""

def shell_game(start_int, shuffle_list) -> int:
    pos = start_int
    for each in shuffle_list:
        if pos == each[0]:
            pos = each[1]
        elif pos == each[1]:
            pos = each[0]
        else:
            continue
    return pos

if __name__ == "__main__":
    """
    Inside of this is the test.
    Outside is the API
    """
    with open("input.txt", 'r') as f_input:
        start_pos = int(f_input.readline())
        shuffles = [tuple(map(int, f_input.readline().split())) for i in range(3)]
        # print(start_pos, shuffles)

    ball_pos = shell_game(start_pos, shuffles)

    with open("output.txt", 'w') as f_output:
        f_output.write(str(ball_pos) + '\n')


w, r= open('output.txt', 'w'), open('input.txt', 'r')
x= r.readline().strip()
for i in (1, 2, 3):
    (a, b) = r.readline().split()
    if x== a:
        x= b
    elif x== b:
        x= a
w.write(x)


inp = int(input())
x1, x2 = [int(i) for i in input().split()]
y1, y2 = [int(i) for i in input().split()]
z1, z2 = [int(i) for i in input().split()]

porz = [0 ,0 ,0 ]

porz[inp-1] = 6

porz1 = porz[:]
porz1[x1 - 1] = porz[x2 - 1]
porz1[x2 - 1] = porz[x1 - 1]

porz2 = porz1[:]
porz2[y1 - 1] = porz1[y2 - 1]
porz2[y2 - 1] = porz1[y1 - 1]

porz3 = porz2[:]
porz3[z1 - 1] = porz2[z2 - 1]
porz3[z2 - 1] = porz2[z1 - 1]

print((porz3.index(6)) +  )


inp = int(input())
x1, x2 = [int(i) for i in input().split()]
y1, y2 = [int(i) for i in input().split()]
z1, z2 = [int(i) for i in input().split()]

porz = [0 ,0 ,0 ]

porz[inp-1] = 6

porz1 = porz[:]
porz1[x1 - 1] = porz[x2 - 1]
porz1[x2 - 1] = porz[x1 - 1]

porz2 = porz1[:]
porz2[y1 - 1] = porz1[y2 - 1]
porz2[y2 - 1] = porz1[y1 - 1]

porz3 = porz2[:]
porz3[z1 - 1] = porz2[z2 - 1]
porz3[z2 - 1] = porz2[z1 - 1]

print(porz3.index(6) + 1)


inp = int(input())
x1, x2 = [int(i) for i in input().split()]
y1, y2 = [int(i) for i in input().split()]
z1, z2 = [int(i) for i in input().split()]

porz = [0 ,0 ,0 ]

porz[inp-1] = 6

porz1 = porz[:]
porz1[x1 - 1] = porz[x2 - 1]
porz1[x2 - 1] = porz[x1 - 1]

porz2 = porz1[:]
porz2[y1 - 1] = porz1[y2 - 1]
porz2[y2 - 1] = porz1[y1 - 1]

porz3 = porz2[:]
porz3[z1 - 1] = porz2[z2 - 1]
porz3[z2 - 1] = porz2[z1 - 1]

print((porz3.index(6)) + 1)


inp = int(input())
x1, x2 = [int(i) for i in input().split()]
y1, y2 = [int(i) for i in input().split()]
z1, z2 = [int(i) for i in input().split()]

porz = [0 ,0 ,0 ]

porz[inp-1] = 6

porz1 = porz[:]
porz1[x1 - 1] = porz[x2 - 1]
porz1[x2 - 1] = porz[x1 - 1]

porz2 = porz1[:]
porz2[y1 - 1] = porz1[y2 - 1]
porz2[y2 - 1] = porz1[y1 - 1]

porz3 = porz2[:]
porz3[z1 - 1] = porz2[z2 - 1]
porz3[z2 - 1] = porz2[z1 - 1]

print((porz3.index(6)) +   1)


inp = int(input())
x1, x2 = [int(i) for i in input().split()]
y1, y2 = [int(i) for i in input().split()]
z1, z2 = [int(i) for i in input().split()]

porz = [0 ,0 ,0 ]

porz[inp-1] = "x"

porz1 = porz[:]
porz1[x1 - 1] = porz[x2 - 1]
porz1[x2 - 1] = porz[x1 - 1]

porz2 = porz1[:]
porz2[x1 - 1] = porz1[x2 - 1]
porz2[x2 - 1] = porz1[x1 - 1]

porz3 = porz2[:]
porz3[x1 - 1] = porz2[x2 - 1]
porz3[x2 - 1] = porz2[x1 - 1]

print(porz3.index("x") + 1)


r = open('input.txt', "r")
w = open('output.txt', "w")

inp = int(r.readline())
x1, x2 = [int(i) for i in r.readline().split()]
y1, y2 = [int(i) for i in r.readline().split()]
z1, z2 = [int(i) for i in r.readline().split()]

porz = [0 ,0 ,0 ]

porz[inp-1] = "x"

porz1 = porz[:]
porz1[x1 - 1] = porz[x2 - 1]
porz1[x2 - 1] = porz[x1 - 1]

porz2 = porz1[:]
porz2[x1 - 1] = porz1[x2 - 1]
porz2[x2 - 1] = porz1[x1 - 1]

porz3 = porz2[:]
porz3[x1 - 1] = porz2[x2 - 1]
porz3[x2 - 1] = porz2[x1 - 1]

w.write(str(porz3.index("x") + 1))
w.close()


r = open('input.txt', "r")
w = open('output.txt', "w")

inp = int(r.readline())
x1, x2 = [int(i) for i in r.readline().split()]
y1, y2 = [int(i) for i in r.readline().split()]
z1, z2 = [int(i) for i in r.readline().split()]

porz = [0 ,0 ,0 ]

porz[inp-1] = 6

porz1 = porz[:]
porz1[x1 - 1] = porz[x2 - 1]
porz1[x2 - 1] = porz[x1 - 1]

porz2 = porz1[:]
porz2[y1 - 1] = porz1[y2 - 1]
porz2[y2 - 1] = porz1[y1 - 1]

porz3 = porz2[:]
porz3[z1 - 1] = porz2[z2 - 1]
porz3[z2 - 1] = porz2[z1 - 1]

w.write(str((porz3.index(6) + 1)))
w.close()