#include<iomanip>
#include<limits>
#include<thread>
#include<utility>
#include<iostream>
#include<string>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<queue>
#include<cmath>
#include<numeric>
#include<cassert>
#include<random>
#include<chrono>
#include<unordered_set>
#include<unordered_map>
#include<fstream>
#include<list>
#include<functional>
#include<bitset>
#include<complex>
#include<tuple>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef pair<ll,ll> pll;
typedef pair<int,int> pi;
typedef pair<double,double> pd;
typedef pair<double,ll> pdl;
#define F first
#define S second
const ll E=1e18+7;
const ll MOD=1000000007;


int main(){
    ll n;
    while(cin>>n){
        if(n==0){break;}
    if(n==2){
        ll p,d,p2,d2;
        cin>>p>>d>>p2>>d2;
        cout<<abs(p2-p)<<endl;
        continue;
    }
    vector<pll> A;
    vector<pll> B;
    for(int i=0;i<n;i++){
        ll p,d;
        cin>>p>>d;
        if(d>1){A.push_back({p,d});}
        else{B.push_back({p,d});}
    }
    sort(A.begin(),A.end());
    sort(B.begin(),B.end());
    vector<ll> dp(B.size()+1,E);
    dp[0]=0;
    ll ans=0;
    for(int i=1;i<A.size();i++){ans+=A[i].F-A[i-1].F;}
    if(A.size()>=2){
        for(int i=1;i+1<A.size();i++){A[i].S-=2;}
        A[0].S-=1;
        A.back().S-=1;
    }
        if(B.size()==0){cout<<ans<<endl; continue;}
    for(int i=0;i<A.size();i++){
        if(A[i].S==0){continue;}
        priority_queue<pll,vector<pll>,greater<pll>> Q;
        Q.push({dp[0],0});
        ll k=abs(A[i].F-B[0].F);
        for(int t=1;t<=B.size();t++){
            while(t-Q.top().S>A[i].S){Q.pop();}
            ll l=dp[t];
            dp[t]=min(dp[t],Q.top().F+k);
            if(t==B.size()){break;}
            Q.push({l-k,t});
            k+=abs(A[i].F-B[t].F);
        }
    }
        if(dp.back()>=E){cout<<-1<<endl; continue;}
    cout<<dp.back()+ans<<endl;
    }
    
    return 0;
}

