Problem:
Problem Statement
You have just arrived in a small country. Unfortunately a huge hurricane swept across the country a few days ago.
The country is made up of $n$ islands, numbered $1$ through $n$. Many bridges connected the islands, but all the bridges were washed away by a flood. People in the islands need new bridges to travel among the islands again.
The problem is cost. The country is not very wealthy. The government has to keep spending down. They asked you, a great programmer, to calculate the minimum cost to rebuild bridges. Write a program to calculate it!
Each bridge connects two islands bidirectionally. Each island $i$ has two parameters $d_i$ and $p_i$. An island $i$ can have at most $d_i$ bridges connected. The cost to build a bridge between an island $i$ and another island $j$ is calculated by $|p_i - p_j|$. Note that it may be impossible to rebuild new bridges within given limitations although people need to travel between any pair of islands over (a sequence of) bridges.
Input
The input is a sequence of datasets.
The number of datasets is less than or equal to $60$.
Each dataset is formatted as follows.
$n$
$p_1$ $d_1$
$p_2$ $d_2$
:
:
$p_n$ $d_n$
Everything in the input is an integer.
$n$ ($2 \leq n \leq 4{,}000$) on the first line indicates the number of islands.
Then $n$ lines follow, which contain the parameters of the islands.
$p_i$ ($1 \leq p_i \leq 10^9$) and $d_i$ ($1 \leq d_i \leq n$) denote the parameters of the island $i$.
The end of the input is indicated by a line with a single zero.
Output
For each dataset, output the minimum cost in a line if it is possible to rebuild bridges within given limitations in the dataset. Otherwise, output $-1$ in a line.
Sample Input
4
1 1
8 2
9 1
14 2
4
181 4
815 4
634 4
370 4
4
52 1
40 1
81 2
73 1
10
330 1
665 3
260 1
287 2
196 3
243 1
815 1
287 3
330 1
473 4
0
Output for the Sample Input
18
634
-1
916

Submitted solutions:

code_snippet: // AOJ #2571 Floating Islands
// 2025.3.19

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll INF = 10000000000000000LL;
const int MAXN = 4005;

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

    while (true) {
        int n;
        cin >> n;
        if (n == 0) break;

        bool sc = false;
        int nA = 0, nB = 0;
        int tot = 0;
        pair<int, int> a[MAXN];
        int b[MAXN];

        for (int i = 0; i < n; ++i) {
            int p, d;
            cin >> p >> d;
            tot += d;
            if (d >= 2) a[++nA] = make_pair(p, d);
            else b[++nB] = p;
        }

        if (n == 1) {
            cout << 0 << endl;
            continue;
        }
        if (tot < 2 * (n - 1)) {
            cout << -1 << endl;
            continue;
        }

        ll ans = 0;
        sort(a + 1, a + 1 + nA);
        sort(b + 1, b + 1 + nB);

        if (nA == 0) {
            ans = abs(b[1] - b[2]);
            sc = true;
        }
        else if (nA == 1) ans = 0;
        else {
            ans = a[nA].first - a[1].first;
            a[1].second--;
            for (int i = 2; i <= nA - 1; ++i) a[i].second -= 2;
            a[nA].second--;
        }

        int tmp = nA;
        nA = 0;
        for (int i = 1; i <= tmp; ++i)
            if (a[i].second > 0) a[++nA] = a[i];

        if (sc) {
            cout << ans << endl;
            continue;
        }

        static ll dp[2][MAXN];
        for (int i = 0; i < 2; ++i)
            for (int j = 0; j < MAXN; ++j) dp[i][j] = INF;
        dp[0][0] = dp[1][0] = 0;

        int pre = 0, cur = 1;
        int assigned = 0;

        pair<int, ll> q[MAXN];
        int front = 1, back = 0;

        auto push = [&](ll value, int id, int w) {
            while (front <= back && q[front].first < id - w) front++;
            while (front <= back && q[back].second >= value) back--;
            q[++back] = make_pair(id, value);
        };

        for (int i = 1; i <= nA; ++i) {
            swap(pre, cur);
            assigned = min(assigned + a[i].second, nB);

            ll ps = 0;
            front = 1, back = 0;
            push(0, 0, a[i].second);
            for (int j = 1; j <= assigned; ++j) {
                ps += abs(b[j] - a[i].first);
                push(dp[pre][j] - ps, j, a[i].second);
                dp[cur][j] = q[front].second + ps;
            }
        }
        ans += dp[cur][nB];
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 130
memory_kb: 3316
final_rank: 1

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<deque>
using namespace std;

typedef long long ll;
typedef pair<int, int> P;

const ll INF = 1e18;

int n;
void solve() {
    vector<int> p(n), d(n);
    for (int i = 0; i < n; i++) cin >> p[i] >> d[i];
    
    int s = 0;
    for (int i = 0; i < n; i++) s += d[i];
    
    if (s < 2 * n - 2) {
        cout << -1 << "\n";
        return;
    }
    
    vector<int> v0;
    vector<P> vp;
    
    for (int i = 0; i < n; i++) {
        if (d[i] == 1) v0.push_back(p[i]);
        else vp.push_back({ p[i], d[i] });
    }
    
    sort(v0.begin(), v0.end());
    sort(vp.begin(), vp.end());
    
    if (n == 2) {
        cout << abs(v0[1] - v0[0]) << "\n"; 
        return;
    }

    ll ans = vp.back().first - vp[0].first;
    if (vp.size() > 1) {
        for (int i = 0; i < vp.size(); i++) {
            if (i == 0 || i == vp.size() - 1) vp[i].second--;
            else vp[i].second -= 2;
        }
    }

    vector<ll> dp(v0.size() + 1, INF);
    dp[0] = 0;
    
    for (int i = 0; i < vp.size(); i++) {
        int c = vp[i].second;
        deque<pair<ll, int>> deq;
        ll ad = 0;

        for (int j = 0; j <= v0.size(); j++) {
            ll val = dp[j] - ad;
            while (!deq.empty() && deq.back().first > val) {
                deq.pop_back();
            }
            deq.push_back({ val, j });
            
            while (deq.front().second < j - c) {
                deq.pop_front();
            }

            dp[j] = deq.front().first + ad;
            if (j < v0.size()) {
                ad += abs(v0[j] - vp[i].first);
            }
        }
    }

    ans += dp[v0.size()];
    cout << ans << "\n";
}

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

    while (cin >> n && n) solve();

    return 0;
}
accuracy: 1
time_ms: 230
memory_kb: 3532
final_rank: 2

code_snippet: #include<cstdio>
#include<vector>
#include<utility>
#include<algorithm>

using namespace std;

const long long inf=1e16;

typedef pair<int,int> P;

P ps[4040];
int N;

vector<int> p1,n1,p2;

vector<int> xs;
vector<int> nearest;
vector<vector<long long> > dp;
vector<long long> tmp;

void init(){
	p1.clear();
	n1.clear();
	p2.clear();
	xs.clear();
	nearest.clear();
	dp.clear();
}

int main(){
	while(true){
		scanf("%d",&N);
		if(N==0) break;
		init();
		for(int i=0;i<N;i++){
			int p,d;
			scanf("%d%d",&p,&d);
			ps[i]=P(p,d);
		}
		sort(ps,ps+N);
		if(N==2){
			printf("%d\r\n",ps[1].first-ps[0].first);
			continue;
		}
		for(int i=0;i<N;i++){
			if(ps[i].second==1){
				p2.push_back(ps[i].first);
			}else{
				p1.push_back(ps[i].first);
				n1.push_back(ps[i].second);
			}
		}
		if(n1.size()==0){
			printf("-1\r\n");
			continue;
		}else if(n1.size()==1){
			if(n1[0]<p2.size()){
				printf("-1\r\n");
			}else{
				long long ans=0;
				for(int i=0;i<p2.size();i++){
					int tmp=abs(p2[i]-p1[0]);
					ans+=tmp;
				}
				printf("%lld\r\n",ans);
			}
			continue;
		}else if(p2.size()==0){
			printf("%d\r\n",p1[p1.size()-1]-p1[0]);
			continue;
		}
		int cnt=0;
		for(int i=0;i<n1.size();i++){
			if(i==0||i+1==n1.size()){
				n1[i]--;
			}else{
				n1[i]-=2;
			}
			cnt+=n1[i];
		}
		if(cnt<p2.size()){
			printf("-1\r\n");
			continue;
		}
		for(int i=0;i<p1.size();i++){
			for(int j=0;j<n1[i];j++){
				xs.push_back(p1[i]);
			}
		}
		for(int i=0;i<p2.size();i++){
			int id=distance(xs.begin(),lower_bound(xs.begin(),xs.end(),p2[i]));
			if(id!=xs.size()&&id!=0){
				int r=abs(xs[id]-p2[i]);
				int l=abs(xs[id-1]-p2[i]);
				if(r>l) id--;
			}
			nearest.push_back(id);
		}
		int l=p2.size();
		tmp.clear();
		for(int i=0;i<2*l+1;i++) tmp.push_back(inf);
		for(int i=0;i<l;i++) dp.push_back(tmp);
		for(int i=0;i<2*l+1;i++){
			int k=nearest[0]+i-l;
			if(k>=0&&k<xs.size()){
				dp[0][i]=abs(xs[k]-p2[0]);
			}
			if(i>0) dp[0][i]=min(dp[0][i],dp[0][i-1]);
		}
		for(int i=1;i<l;i++){
			for(int j=0;j<2*l+1;j++){
				int k=nearest[i]+j-l-1;
				if(k+1<0||k+1>=xs.size()){
					if(j>0){
						dp[i][j]=min(dp[i][j],dp[i][j-1]);
					}
					continue;
				}
				int d=k-nearest[i-1];
				int prev=d+l;
				if(prev>l*2) prev=l*2;
				if(prev<0){
					if(j>0){
						dp[i][j]=min(dp[i][j],dp[i][j-1]);
					}
					continue;
				}
				if(dp[i-1][prev]==inf){
					if(j>0){
						dp[i][j]=min(dp[i][j],dp[i][j-1]);
						continue;
					}
				}
				dp[i][j]=dp[i-1][prev]+abs(xs[k+1]-p2[i]);
				if(j>0) dp[i][j]=min(dp[i][j],dp[i][j-1]);
			}
		}
		printf("%lld\r\n",dp[l-1][2*l]+p1[p1.size()-1]-p1[0]);
	}
	return 0;
}
accuracy: 1
time_ms: 1920
memory_kb: 292608
final_rank: 18

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

const long long INF = (3LL << 59);

struct island {
	long long p; int d;
};

long long solve(int N, const vector<island>& X) {
	if (N == 2) {
		return X[1].p - X[0].p;
	}
	int degsum = 0;
	for (int i = 0; i < N; i++) {
		degsum += X[i].d;
	}
	if (degsum < 2 * N - 2) {
		return -1;
	}
	vector<int> v1, v2;
	for (int i = 0; i < N; i++) {
		if (X[i].d == 1) {
			v1.push_back(i);
		}
		else {
			v2.push_back(i);
		}
	}
	vector<long long> v1s(v1.size() + 1);
	vector<long long> v2s(v2.size() + 1);
	for (int i = 0; i < v1.size(); i++) {
		v1s[i + 1] = v1s[i] + X[v1[i]].p;
	}
	for (int i = 0; i < v2.size(); i++) {
		v2s[i + 1] = v2s[i] + X[v2[i]].p;
	}
	vector<long long> dp(v1.size() + 1, INF);
	dp[0] = 0;
	for (int i = 0; i < v2.size(); i++) {
		vector<long long> ndp = dp;
		vector<long long> dpval1 = dp;
		vector<long long> dpval2 = dp;
		for (int j = 0; j <= v1.size(); j++) {
			dpval1[j] += -v1s[j] + X[v2[i]].p * j;
			dpval2[j] += v1s[j] - X[v2[i]].p * j;
		}
		deque<int> que1; int l1 = 0, r1 = 0;
		deque<int> que2; int l2 = 0, r2 = 0;
		auto set1 = [&](int l, int r) -> void {
			while (r1 != r) {
				while (!que1.empty() && dpval1[que1.back()] > dpval1[r1]) {
					que1.pop_back();
				}
				que1.push_back(r1);
				r1 += 1;
			}
			while (l1 != l) {
				if (que1.front() == l1) {
					que1.pop_front();
				}
				l1 += 1;
			}
		};
		auto set2 = [&](int l, int r) -> void {
			while (r2 != r) {
				while (!que2.empty() && dpval2[que2.back()] > dpval2[r2]) {
					que2.pop_back();
				}
				que2.push_back(r2);
				r2 += 1;
			}
			while (l2 != l) {
				if (que2.front() == l2) {
					que2.pop_front();
				}
				l2 += 1;
			}
		};
		int rem = X[v2[i]].d - 2 + (i == 0) + (i == v2.size() - 1);
		int pos = 0;
		for (int j = 0; j <= int(v1.size()); j++) {
			while (pos != v1.size() && v1[pos] < v2[i]) {
				pos += 1;
			}
			int l = max(j - rem, 0);
			int mid = max(min(pos, j), l);
			set1(mid, j);
			set2(l, mid);
			if (!que1.empty()) {
				ndp[j] = min(ndp[j], dpval1[que1.front()] + v1s[j] - X[v2[i]].p * j);
			}
			if (!que2.empty()) {
				ndp[j] = min(ndp[j], dpval2[que2.front()] + v1s[j] - v1s[mid] * 2 - X[v2[i]].p * (j - mid * 2));
			}
		}
		dp = ndp;
	}
	return dp[v1.size()] + (X[v2.back()].p - X[v2.front()].p);
}

int main() {
	while (true) {
		int N;
		cin >> N;
		if (N == 0) {
			break;
		}
		vector<island> X(N);
		for (int i = 0; i < N; i++) {
			cin >> X[i].p >> X[i].d;
			X[i].d = min(X[i].d, N - 1);
		}
		sort(X.begin(), X.end(), [](const island& x1, const island& x2) {
			return x1.p < x2.p;
		});
		long long ans = solve(N, X);
		cout << ans << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 690
memory_kb: 3648
final_rank: 7

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int N;
int main()
{
	while(cin>>N,N)
	{
		vector<pair<int,int> >PD(N);
		int sd=0;
		for(int i=0;i<N;i++)
		{
			int p,d;cin>>p>>d;
			d=min(d,N-1);
			PD[i]=make_pair(p,d);
			sd+=d;
		}
		if(sd<(N-1)*2)
		{
			cout<<-1<<endl;
			continue;
		}
		vector<int>one;
		vector<pair<int,int> >two;
		sort(PD.begin(),PD.end());
		for(int i=0;i<PD.size();i++)
		{
			if(i>0&&i+1<PD.size()&&PD[i].second==1)one.push_back(PD[i].first);
			else two.push_back(PD[i]);
		}
		long long ans=0;
		for(int i=0;i+1<two.size();i++)
		{
			two[i].second--;
			two[i+1].second--;
			ans+=two[i+1].first-two[i].first;
		}
		vector<long long>dp(one.size()+1,(long long)1e18);
		dp[0]=0;
		vector<long long>S(one.size()+1,0LL);
		for(int i=0;i<one.size();i++)S[i+1]=S[i]+one[i];
		vector<pair<long long,int> >Q;
		for(pair<int,int>p:two)
		{
			vector<long long>nxt=dp;
			Q.clear();
			int qi=0;
			long long add=0;
			for(int i=0;i<=one.size();i++)
			{
				if(qi<Q.size())nxt[i]=min(nxt[i],Q[qi].first+add);
				if(i==one.size())break;
				pair<long long,int>q=make_pair(dp[i]-add,i+p.second);
				while(qi<Q.size()&&Q.back().first>=q.first)Q.pop_back();
				Q.push_back(q);
				add+=abs(one[i]-p.first);
				while(qi<Q.size()&&Q[qi].second<=i)qi++;
			}
			dp=nxt;
		}
		cout<<ans+dp[one.size()]<<"\n";
	}
}
accuracy: 1
time_ms: 310
memory_kb: 3280
final_rank: 4

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int N;
int main()
{
	while(cin>>N,N)
	{
		vector<pair<int,int> >PD(N);
		int sd=0;
		for(int i=0;i<N;i++)
		{
			int p,d;cin>>p>>d;
			d=min(d,N-1);
			PD[i]=make_pair(p,d);
			sd+=d;
		}
		if(sd<(N-1)*2)
		{
			cout<<-1<<endl;
			continue;
		}
		vector<int>one;
		vector<pair<int,int> >two;
		sort(PD.begin(),PD.end());
		for(int i=0;i<PD.size();i++)
		{
			if(i>0&&i+1<PD.size()&&PD[i].second==1)one.push_back(PD[i].first);
			else two.push_back(PD[i]);
		}
		long long ans=0;
		for(int i=0;i+1<two.size();i++)
		{
			two[i].second--;
			two[i+1].second--;
			ans+=two[i+1].first-two[i].first;
		}
		vector<long long>dp(one.size()+1,(long long)1e18);
		dp[0]=0;
		vector<long long>S(one.size()+1,0LL);
		for(int i=0;i<one.size();i++)S[i+1]=S[i]+one[i];
		vector<pair<long long,int> >Q;
		for(pair<int,int>p:two)
		{
			vector<long long>nxt=dp;
			int id=lower_bound(one.begin(),one.end(),p.first)-one.begin();
			Q.clear();
			for(int i=0;i<id;i++)
			{
				if(i+p.second<=id)
				{
					nxt[i+p.second]=min(nxt[i+p.second],
						dp[i]+(long long)p.second*p.first-(S[i+p.second]-S[i]));
				}
				else
				{
					long long nc=dp[i]+(long long)(id-i)*p.first-(S[id]-S[i]);
					pair<long long,int>q=make_pair(nc,i+p.second);
					while(!Q.empty()&&Q.back().first>=q.first)Q.pop_back();
					Q.push_back(q);
				}
			}
			int qi=0;
			long long add=0;
			for(int i=id;i<=one.size();i++)
			{
				if(qi<Q.size())nxt[i]=min(nxt[i],Q[qi].first+add);
				if(i==one.size())break;
				pair<long long,int>q=make_pair(dp[i]-add,i+p.second);
				while(qi<Q.size()&&Q.back().first>=q.first)Q.pop_back();
				Q.push_back(q);
				add+=one[i]-p.first;
				while(qi<Q.size()&&Q[qi].second<=i)qi++;
			}
			dp=nxt;
		}
		cout<<ans+dp[one.size()]<<"\n";
	}
}
accuracy: 1
time_ms: 260
memory_kb: 3316
final_rank: 3

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
using namespace std;
int N;
int main()
{
	while(cin>>N,N)
	{
		vector<pair<int,int> >PD(N);
		int sd=0;
		for(int i=0;i<N;i++)
		{
			int p,d;cin>>p>>d;
			d=min(d,N-1);
			PD[i]=make_pair(p,d);
			sd+=d;
		}
		if(sd<(N-1)*2)
		{
			cout<<-1<<endl;
			continue;
		}
		vector<int>one;
		vector<pair<int,int> >two;
		sort(PD.begin(),PD.end());
		for(int i=0;i<PD.size();i++)
		{
			if(i>0&&i+1<PD.size()&&PD[i].second==1)one.push_back(PD[i].first);
			else two.push_back(PD[i]);
		}
		long long ans=0;
		for(int i=0;i+1<two.size();i++)
		{
			two[i].second--;
			two[i+1].second--;
			ans+=two[i+1].first-two[i].first;
		}
		vector<long long>dp(one.size()+1,(long long)1e18);
		dp[0]=0;
		vector<long long>S(one.size()+1,0LL);
		for(int i=0;i<one.size();i++)S[i+1]=S[i]+one[i];
		for(pair<int,int>p:two)
		{
			vector<long long>nxt=dp;
			int id=lower_bound(one.begin(),one.end(),p.first)-one.begin();
			priority_queue<pair<long long,int>,vector<pair<long long,int> >,greater<pair<long long,int> > >Q;
			for(int i=0;i<id;i++)
			{
				if(i+p.second<=id)
				{
					nxt[i+p.second]=min(nxt[i+p.second],
						dp[i]+(long long)p.second*p.first-(S[i+p.second]-S[i]));
				}
				else
				{
					long long nc=dp[i]+(long long)(id-i)*p.first-(S[id]-S[i]);
					Q.push(make_pair(nc,i+p.second));
				}
			}
			long long add=0;
			for(int i=id;i<=one.size();i++)
			{
				if(!Q.empty())nxt[i]=min(nxt[i],Q.top().first+add);
				if(i==one.size())break;
				Q.push(make_pair(dp[i]-add,i+p.second));
				add+=one[i]-p.first;
				while(!Q.empty()&&Q.top().second<=i)Q.pop();
			}
			dp=nxt;
		}
		cout<<ans+dp[one.size()]<<"\n";
	}
}
accuracy: 1
time_ms: 950
memory_kb: 3212
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return true; } return false; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return true; } return false; }
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define mp make_pair
#define si(x) int(x.size())
const int mod=998244353,MAX=4005,INF=1<<28;

// フローのみ

// from: https://gist.github.com/yosupo06/ddd51afb727600fd95d9d8ad6c3c80c9
// (based on AtCoder STL)

#ifndef ATCODER_INTERNAL_QUEUE_HPP
#define ATCODER_INTERNAL_QUEUE_HPP 1
#include <vector>
namespace atcoder {
    namespace internal {
        template <class T> struct simple_queue {
            std::vector<T> payload;
            int pos = 0;
            void reserve(int n) { payload.reserve(n); }
            int size() const { return int(payload.size()) - pos; }
            bool empty() const { return pos == int(payload.size()); }
            void push(const T& t) { payload.push_back(t); }
            T& front() { return payload[pos]; }
            void clear() {
                payload.clear();
                pos = 0;
            }
            void pop() { pos++; }
        };
    }  // namespace internal
}  // namespace atcoder
#endif  // ATCODER_INTERNAL_QUEUE_HPP

#ifndef ATCODER_MAXFLOW_HPP
#define ATCODER_MAXFLOW_HPP 1
#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>
namespace atcoder {
    template <class Cap> struct mf_graph {
    public:
        mf_graph() : _n(0) {}
        mf_graph(int n) : _n(n), g(n) {}
        int add_edge(int from, int to, Cap cap) {
            assert(0 <= from && from < _n);
            assert(0 <= to && to < _n);
            assert(0 <= cap);
            int m = int(pos.size());
            pos.push_back({from, int(g[from].size())});
            g[from].push_back(_edge{to, int(g[to].size()), cap});
            g[to].push_back(_edge{from, int(g[from].size()) - 1, 0});
            return m;
        }
        struct edge {
            int from, to;
            Cap cap, flow;
        };
        edge get_edge(int i) {
            int m = int(pos.size());
            assert(0 <= i && i < m);
            auto _e = g[pos[i].first][pos[i].second];
            auto _re = g[_e.to][_e.rev];
            return edge{pos[i].first, _e.to, _e.cap + _re.cap, _re.cap};
        }
        std::vector<edge> edges() {
            int m = int(pos.size());
            std::vector<edge> result;
            for (int i = 0; i < m; i++) {
                result.push_back(get_edge(i));
            }
            return result;
        }
        void change_edge(int i, Cap new_cap, Cap new_flow) {
            int m = int(pos.size());
            assert(0 <= i && i < m);
            assert(0 <= new_flow && new_flow <= new_cap);
            auto& _e = g[pos[i].first][pos[i].second];
            auto& _re = g[_e.to][_e.rev];
            _e.cap = new_cap - new_flow;
            _re.cap = new_flow;
        }
        Cap flow(int s, int t) {
            return flow(s, t, std::numeric_limits<Cap>::max());
        }
        Cap flow(int s, int t, Cap flow_limit) {
            assert(0 <= s && s < _n);
            assert(0 <= t && t < _n);
            std::vector<int> level(_n), iter(_n);
            internal::simple_queue<int> que;
            auto bfs = [&]() {
                std::fill(level.begin(), level.end(), -1);
                level[s] = 0;
                que.clear();
                que.push(s);
                while (!que.empty()) {
                    int v = que.front();
                    que.pop();
                    for (auto e : g[v]) {
                        if (e.cap == 0 || level[e.to] >= 0) continue;
                        level[e.to] = level[v] + 1;
                        if (e.to == t) return;
                        que.push(e.to);
                    }
                }
            };
            auto dfs = [&](auto self, int v, Cap up) {
                if (v == s) return up;
                Cap res = 0;
                int level_v = level[v];
                for (int& i = iter[v]; i < int(g[v].size()); i++) {
                    _edge& e = g[v][i];
                    if (level_v <= level[e.to] || g[e.to][e.rev].cap == 0) continue;
                    Cap d =
                    self(self, e.to, std::min(up - res, g[e.to][e.rev].cap));
                    if (d <= 0) continue;
                    g[v][i].cap += d;
                    g[e.to][e.rev].cap -= d;
                    res += d;
                    if (res == up) break;
                }
                return res;
            };
            Cap flow = 0;
            while (flow < flow_limit) {
                bfs();
                if (level[t] == -1) break;
                std::fill(iter.begin(), iter.end(), 0);
                while (flow < flow_limit) {
                    Cap f = dfs(dfs, t, flow_limit - flow);
                    if (!f) break;
                    flow += f;
                }
            }
            return flow;
        }
        std::vector<bool> min_cut(int s) {
            std::vector<bool> visited(_n);
            internal::simple_queue<int> que;
            que.push(s);
            while (!que.empty()) {
                int p = que.front();
                que.pop();
                visited[p] = true;
                for (auto e : g[p]) {
                    if (e.cap && !visited[e.to]) {
                        visited[e.to] = true;
                        que.push(e.to);
                    }
                }
            }
            return visited;
        }
    private:
        int _n;
        struct _edge {
            int to, rev;
            Cap cap;
        };
        std::vector<std::pair<int, int>> pos;
        std::vector<std::vector<_edge>> g;
    };
}  // namespace atcoder
#endif  // ATCODER_MAXFLOW_HPP
#ifndef ATCODER_MINCOSTFLOW_HPP
#define ATCODER_MINCOSTFLOW_HPP 1
#include <algorithm>
#include <cassert>
#include <limits>
#include <queue>
#include <vector>
namespace atcoder {
    template <class Cap, class Cost> struct mcf_graph {
    public:
        mcf_graph() {}
        mcf_graph(int n) : _n(n), g(n) {}
        int add_edge(int from, int to, Cap cap, Cost cost) {
            assert(0 <= from && from < _n);
            assert(0 <= to && to < _n);
            int m = int(pos.size());
            pos.push_back({from, int(g[from].size())});
            g[from].push_back(_edge{to, int(g[to].size()), cap, cost});
            g[to].push_back(_edge{from, int(g[from].size()) - 1, 0, -cost});
            return m;
        }
        struct edge {
            int from, to;
            Cap cap, flow;
            Cost cost;
        };
        edge get_edge(int i) {
            int m = int(pos.size());
            assert(0 <= i && i < m);
            auto _e = g[pos[i].first][pos[i].second];
            auto _re = g[_e.to][_e.rev];
            return edge{
                pos[i].first, _e.to, _e.cap + _re.cap, _re.cap, _e.cost,
            };
        }
        std::vector<edge> edges() {
            int m = int(pos.size());
            std::vector<edge> result(m);
            for (int i = 0; i < m; i++) {
                result[i] = get_edge(i);
            }
            return result;
        }
        std::pair<Cap, Cost> flow(int s, int t) {
            return flow(s, t, std::numeric_limits<Cap>::max());
        }
        std::pair<Cap, Cost> flow(int s, int t, Cap flow_limit) {
            return slope(s, t, flow_limit).back();
        }
        std::vector<std::pair<Cap, Cost>> slope(int s, int t) {
            return slope(s, t, std::numeric_limits<Cap>::max());
        }
        std::vector<std::pair<Cap, Cost>> slope(int s, int t, Cap flow_limit) {
            assert(0 <= s && s < _n);
            assert(0 <= t && t < _n);
            assert(s != t);
            // variants (C = maxcost):
            // -(n-1)C <= dual[s] <= dual[i] <= dual[t] = 0
            // reduced cost (= e.cost + dual[e.from] - dual[e.to]) >= 0 for all edge
            std::vector<Cost> dual(_n, 0), dist(_n);
            std::vector<int> pv(_n), pe(_n);
            std::vector<bool> vis(_n);
            auto dual_ref = [&]() {
                std::fill(dist.begin(), dist.end(),
                          std::numeric_limits<Cost>::max());
                std::fill(pv.begin(), pv.end(), -1);
                std::fill(pe.begin(), pe.end(), -1);
                std::fill(vis.begin(), vis.end(), false);
                struct Q {
                    Cost key;
                    int to;
                    bool operator<(Q r) const { return key > r.key; }
                };
                std::priority_queue<Q> que;
                dist[s] = 0;
                que.push(Q{0, s});
                while (!que.empty()) {
                    int v = que.top().to;
                    que.pop();
                    if (vis[v]) continue;
                    vis[v] = true;
                    if (v == t) break;
                    // dist[v] = shortest(s, v) + dual[s] - dual[v]
                    // dist[v] >= 0 (all reduced cost are positive)
                    // dist[v] <= (n-1)C
                    for (int i = 0; i < int(g[v].size()); i++) {
                        auto e = g[v][i];
                        if (vis[e.to] || !e.cap) continue;
                        // |-dual[e.to] + dual[v]| <= (n-1)C
                        // cost <= C - -(n-1)C + 0 = nC
                        Cost cost = e.cost - dual[e.to] + dual[v];
                        if (dist[e.to] - dist[v] > cost) {
                            dist[e.to] = dist[v] + cost;
                            pv[e.to] = v;
                            pe[e.to] = i;
                            que.push(Q{dist[e.to], e.to});
                        }
                    }
                }
                if (!vis[t]) {
                    return false;
                }
                for (int v = 0; v < _n; v++) {
                    if (!vis[v]) continue;
                    // dual[v] = dual[v] - dist[t] + dist[v]
                    //         = dual[v] - (shortest(s, t) + dual[s] - dual[t]) + (shortest(s, v) + dual[s] - dual[v])
                    //         = - shortest(s, t) + dual[t] + shortest(s, v)
                    //         = shortest(s, v) - shortest(s, t) >= 0 - (n-1)C
                    dual[v] -= dist[t] - dist[v];
                }
                return true;
            };
            Cap flow = 0;
            Cost cost = 0, prev_cost = -1;
            std::vector<std::pair<Cap, Cost>> result;
            result.push_back({flow, cost});
            while (flow < flow_limit) {
                if (!dual_ref()) break;
                Cap c = flow_limit - flow;
                for (int v = t; v != s; v = pv[v]) {
                    c = std::min(c, g[pv[v]][pe[v]].cap);
                }
                for (int v = t; v != s; v = pv[v]) {
                    auto& e = g[pv[v]][pe[v]];
                    e.cap -= c;
                    g[v][e.rev].cap += c;
                }
                Cost d = -dual[s];
                flow += c;
                cost += c * d;
                if (prev_cost == d) {
                    result.pop_back();
                }
                result.push_back({flow, cost});
                prev_cost = d;
            }
            return result;
        }
    private:
        int _n;
        struct _edge {
            int to, rev;
            Cap cap;
            Cost cost;
        };
        std::vector<std::pair<int, int>> pos;
        std::vector<std::vector<_edge>> g;
    };
}  // namespace atcoder
#endif  // ATCODER_MINCOSTFLOW_HPP

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    while(1){
        int N;cin>>N;
        if(N==0) break;
        vector<pair<ll,ll>> A(N);
        for(int i=0;i<N;i++) cin>>A[i].fi>>A[i].se;
        sort(all(A));
        ll ans=0,deg=0;
        for(int i=0;i<N;i++){
            deg+=A[i].se;
        }
        if(deg<2*(N-1)){
            cout<<-1<<"\n";
            continue;
        }
        ans=A.back().fi-A.front().fi;
        
        atcoder::mcf_graph<int,ll> G(N+2);
        int s=N,t=s+1;
        
        for(int i=1;i<N-1;i++){
            if(A[i].se==1){
                G.add_edge(s,i,1,0);
            }
        }
        
        for(int i=0;i<N-1;i++){
            G.add_edge(i,i+1,N,A[i+1].fi-A[i].fi);
            G.add_edge(i+1,i,N,A[i+1].fi-A[i].fi);
        }
        for(int j=0;j<N;j++){
            int can=A[j].se;
            if(j==0||j==N-1) can--;
            else can-=2;
            if(can>0) G.add_edge(j,t,can,0);
        }
        
        cout<<ans+G.flow(s,t).se<<"\n";
    }
}
accuracy: 1
time_ms: 7470
memory_kb: 4736
final_rank: 19

code_snippet: #pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include<iostream>
#include<string>
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
#include<functional>
#include<iomanip>
#include<queue>
#include<ciso646>
#include<random>
#include<map>
#include<set>
#include<bitset>
#include<stack>
#include<unordered_map>
#include<unordered_set>
#include<utility>
#include<cassert>
#include<complex>
#include<numeric>
#include<array>
#include<chrono>
using namespace std;

//#define int long long
typedef long long ll;

typedef unsigned long long ul;
typedef unsigned int ui;
constexpr ll mod = 1000000007;
const ll INF = mod * mod;
typedef pair<int, int>P;

#define rep(i,n) for(int i=0;i<n;i++)
#define per(i,n) for(int i=n-1;i>=0;i--)
#define Rep(i,sta,n) for(int i=sta;i<n;i++)
#define rep1(i,n) for(int i=1;i<=n;i++)
#define per1(i,n) for(int i=n;i>=1;i--)
#define Rep1(i,sta,n) for(int i=sta;i<=n;i++)
#define all(v) (v).begin(),(v).end()
typedef pair<ll, ll> LP;

template<typename T>
void chmin(T& a, T b) {
	a = min(a, b);
}
template<typename T>
void chmax(T& a, T b) {
	a = max(a, b);
}
template<typename T>
void cinarray(vector<T>& v) {
	rep(i, v.size())cin >> v[i];
}
template<typename T>
void coutarray(vector<T>& v) {
	rep(i, v.size()) {
		if (i > 0)cout << " "; cout << v[i];
	}
	cout << "\n";
}
ll mod_pow(ll x, ll n, ll m = mod) {
	if (n < 0) {
		ll res = mod_pow(x, -n, m);
		return mod_pow(res, m - 2, m);
	}
	if (abs(x) >= m)x %= m;
	if (x < 0)x += m;
	if (x == 0)return 0;
	ll res = 1;
	while (n) {
		if (n & 1)res = res * x % m;
		x = x * x % m; n >>= 1;
	}
	return res;
}
struct modint {
	int n;
	modint() :n(0) { ; }
	modint(ll m) {
		if (m < 0 || mod <= m) {
			m %= mod; if (m < 0)m += mod;
		}
		n = m;
	}
	operator int() { return n; }
};
bool operator==(modint a, modint b) { return a.n == b.n; }
modint operator+=(modint& a, modint b) { a.n += b.n; if (a.n >= mod)a.n -= mod; return a; }
modint operator-=(modint& a, modint b) { a.n -= b.n; if (a.n < 0)a.n += mod; return a; }
modint operator*=(modint& a, modint b) { a.n = ((ll)a.n * b.n) % mod; return a; }
modint operator+(modint a, modint b) { return a += b; }
modint operator-(modint a, modint b) { return a -= b; }
modint operator*(modint a, modint b) { return a *= b; }
modint operator^(modint a, ll n) {
	if (n == 0)return modint(1);
	modint res = (a * a) ^ (n / 2);
	if (n % 2)res = res * a;
	return res;
}

ll inv(ll a, ll p) {
	return (a == 1 ? 1 : (1 - p * inv(p % a, a)) / a + p);
}
modint operator/(modint a, modint b) { return a * modint(inv(b, mod)); }
modint operator/=(modint& a, modint b) { a = a / b; return a; }
const int max_n = 1 << 10;
modint fact[max_n], factinv[max_n];
void init_f() {
	fact[0] = modint(1);
	for (int i = 0; i < max_n - 1; i++) {
		fact[i + 1] = fact[i] * modint(i + 1);
	}
	factinv[max_n - 1] = modint(1) / fact[max_n - 1];
	for (int i = max_n - 2; i >= 0; i--) {
		factinv[i] = factinv[i + 1] * modint(i + 1);
	}
}
modint comb(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[b] * factinv[a - b];
}
modint combP(int a, int b) {
	if (a < 0 || b < 0 || a < b)return 0;
	return fact[a] * factinv[a - b];
}

ll gcd(ll a, ll b) {
	a = abs(a); b = abs(b);
	if (a < b)swap(a, b);
	while (b) {
		ll r = a % b; a = b; b = r;
	}
	return a;
}
typedef long double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-8;
const ld pi = acosl(-1.0);
int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

//-----------------------------------

int n;
void solve() {
	vector<int> p(n), d(n);
	rep(i, n)cin >> p[i] >> d[i];
	int s = 0;
	rep(i, n)s += d[i];
	if (s < 2 * n - 2) {
		cout << -1 << "\n"; return;
	}
	vector<int> v0;
	vector<P> vp;
	rep(i, n) {
		if (d[i] == 1)v0.push_back(p[i]);
		else vp.push_back({ p[i],d[i] });
	}
	sort(all(v0));
	sort(all(vp));
	if (n == 2) {
		cout << abs(v0[1] - v0[0]) << "\n"; 
		return;
	}
	ll ans = 0;
	ans = vp.back().first - vp[0].first;
	if (vp.size() > 1) {
		rep(i, vp.size()) {
			if (i == 0 || i == vp.size() - 1)vp[i].second--;
			else vp[i].second -= 2;
		}
	}
	vector<ll> dp(v0.size() + 1, INF);
	dp[0] = 0;
	rep(i, vp.size()) {
		int c = vp[i].second;
		deque<LP> deq;
		ll ad = 0;
		rep(j, v0.size() + 1) {
			ll val = dp[j] - ad;
			while (deq.size() && deq.back().first > val) {
				deq.pop_back();
			}
			deq.push_back({ val,j });
			while (deq.front().second < j - c) {
				deq.pop_front();
			}
			dp[j] = deq.front().first + ad;
			if (j < v0.size()) {
				ad += abs(v0[j] - vp[i].first);
			}
		}
	}
	ans += dp[v0.size()];
	cout << ans << "\n";
}


signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout << fixed << setprecision(8);
	//init_f();
	//init();
	//while(true)
	//expr();
	//int t; cin >> t; rep(i, t)
	while(cin>>n,n)
	solve();
	return 0;
}
accuracy: 1
time_ms: 330
memory_kb: 3436
final_rank: 5

code_snippet: #include <iostream>
#include <iomanip>
#include <vector>
#include <array>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <tuple>
#include <cmath>
#include <algorithm>
#include <functional>
#include <numeric>
#include <cfloat>
#include <climits>
#include <cassert>
#include <random>

struct Island {
	int p, d;
};
constexpr long long int INF = LLONG_MAX >> 1;

void set_memo(const Island current, const int from, const int until, const int left, const int right_until, const std::vector<Island>& single, const std::vector<long long int> &prev, std::vector<long long int> &memo, const std::vector<long long int> &sum_diff) {
	if (from == until) return;
	if (prev[right_until] == INF) return;
	const auto mid = (from + until) / 2;
	long long int min = prev[mid];
	int best = std::max(mid, left);
	long long int sum = sum_diff[best] - sum_diff[mid];
	for (int i = best, rest = current.d - best + mid; i < right_until && rest > 0; ++i, --rest) {
		sum += std::abs(current.p - single[i].p);
		if (min > sum + prev[i + 1]) {
			min = sum + prev[i + 1];
			best = i;
		}
	}
	memo[mid] = min;
	set_memo(current, from, mid, left, best + 1, single, prev, memo, sum_diff);
	set_memo(current, mid + 1, until, best, right_until, single, prev, memo, sum_diff);
}
int main(){
	while (true) {
		int n; std::cin >> n; if (n == 0) break;
		std::vector<Island> islands(n), single, many;
		for (auto& i : islands) std::cin >> i.p >> i.d;
		std::sort(islands.begin(), islands.end(), [](Island a, Island b) {return a.p < b.p; });
		for (const auto i : islands) {
			if (i.d == 1) {
				single.push_back(i);
			}
			else {
				many.push_back(i);
			}
		}
		if (many.empty() && single.size() == 2) {
			std::cout << single.back().p - single.front().p << '\n';
			continue;
		}
		long long int cost = 0;
		for (auto i = 1; i < many.size(); ++i) {
			cost += many[i].p - many[i - 1].p;
		}
		long long int count = 0;
		if (many.size() != 1) for (auto i = 0; i < many.size(); ++i) {
			if (i == 0 || i == many.size() - 1) {
				--many[i].d;
			}
			else {
				many[i].d -= 2;
			}
			count += many[i].d;
		}
		else {
			count = many.front().d;
		}
		if (count < single.size()) {
			std::cout << "-1\n";
			continue;
		}
		std::vector<std::vector<long long int>> memo(2, std::vector<long long int>(single.size() + 1, INF));
		std::vector<long long int> sum_diff(single.size() + 1, 0);
		memo.front().back() = memo.back().back() = 0;
		std::reverse(many.begin(), many.end());
		for (auto i = 0; i < many.size(); ++i) {
			for (auto j = 0; j < single.size(); ++j) {
				sum_diff[j + 1] = sum_diff[j] + std::abs(single[j].p - many[i].p);
			}
			set_memo(many[i], 0, single.size(), 0, single.size(), single, memo[i & 1], memo[(i + 1) & 1], sum_diff);
		}
		if (memo[many.size() & 1].front() == INF) {
			std::cout << -1 << '\n';
		}
		else {
			std::cout << (cost + memo[many.size() & 1].front()) << '\n';
		}
	}
}
accuracy: 1
time_ms: 1110
memory_kb: 3296
final_rank: 10

code_snippet: #define NDEBUG
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <vector>

namespace n91 {

  using i8 = std::int_fast8_t;
  using i32 = std::int_fast32_t;
  using i64 = std::int_fast64_t;
  using u8 = std::uint_fast8_t;
  using u32 = std::uint_fast32_t;
  using u64 = std::uint_fast64_t;
  using isize = std::ptrdiff_t;
  using usize = std::size_t;

  struct rep {
    struct itr {
      usize i;
      constexpr itr(const usize i) noexcept : i(i) {}
      void operator++() noexcept { ++i; }
      constexpr usize operator*() const noexcept { return i; }
      constexpr bool operator!=(const itr x) const noexcept { return i != x.i; }
    };
    const itr f, l;
    constexpr rep(const usize f, const usize l) noexcept
      : f(std::min(f, l)), l(l) {}
    constexpr auto begin() const noexcept { return f; }
    constexpr auto end() const noexcept { return l; }
  };
  struct revrep {
    struct itr {
      usize i;
      constexpr itr(const usize i) noexcept : i(i) {}
      void operator++() noexcept { --i; }
      constexpr usize operator*() const noexcept { return i; }
      constexpr bool operator!=(const itr x) const noexcept { return i != x.i; }
    };
    const itr f, l;
    constexpr revrep(const usize f, const usize l) noexcept
      : f(l - 1), l(std::min(f, l) - 1) {}
    constexpr auto begin() const noexcept { return f; }
    constexpr auto end() const noexcept { return l; }
  };
  template <class T> auto md_vec(const usize n, const T& value) {
    return std::vector<T>(n, value);
  }
  template <class... Args> auto md_vec(const usize n, Args... args) {
    return std::vector<decltype(md_vec(args...))>(n, md_vec(args...));
  }
  template <class T> constexpr T difference(const T& a, const T& b) noexcept {
    return a < b ? b - a : a - b;
  }
  template <class T> void chmin(T& a, const T& b) noexcept {
    if (b < a)
      a = b;
  }
  template <class T> void chmax(T& a, const T& b) noexcept {
    if (a < b)
      a = b;
  }
  template <class T> T scan() {
    T ret;
    std::cin >> ret;
    return ret;
  }

} // namespace n91
#include <cassert>
#include <stack>

namespace nimi {

  template <class T, class Op> class queue_aggregation {
  private:
    class node {
    public:
      T val, sum;
      node(const T& val, const T& sum) : val(val), sum(sum) {}
    };

    Op op;
    std::stack<node> front_stack, back_stack;

  public:
    queue_aggregation(const Op& op = Op())
      : op(op), front_stack(), back_stack() {}

    bool empty() const { return front_stack.empty() && back_stack.empty(); }

    std::size_t size() const { return front_stack.size() + back_stack.size(); }

    T fold_all() const {
      assert(!empty());
      if (front_stack.empty()) {
        return back_stack.top().sum;
      }
      else if (back_stack.empty()) {
        return front_stack.top().sum;
      }
      else {
        return op(front_stack.top().sum, back_stack.top().sum);
      }
    }

    void push(const T& x) {
      if (back_stack.empty()) {
        back_stack.emplace(x, x);
      }
      else {
        T s{ op(back_stack.top().sum, x) };
        back_stack.emplace(x, s);
      }
    }

    void pop() {
      assert(!empty());
      if (front_stack.empty()) {
        front_stack.emplace(back_stack.top().val, back_stack.top().val);
        back_stack.pop();
        while (!back_stack.empty()) {
          T s{ op(back_stack.top().val, front_stack.top().sum) };
          front_stack.emplace(back_stack.top().val, s);
          back_stack.pop();
        }
      }
      front_stack.pop();
    }
  };

} // namespace nimi

#include <algorithm>
#include <iostream>
#include <utility>

namespace n91 {

  void main_() {
    while (true) {
      static constexpr i64 Inf = std::numeric_limits<i64>::max() / 10;
      const usize n{ scan<usize>() };
      if (n == 0) {
        return;
      }
      struct city_t {
        i64 p;
        usize d;
      };
      std::vector<city_t> city(n);
      for (auto& e : city) {
        std::cin >> e.p >> e.d;
      }
      std::sort(city.begin(), city.end(),
        [](auto l, auto r) { return l.p < r.p; });
      if (n == 2) {
        std::cout << city[1].p - city[0].p << std::endl;
        continue;
      }
      std::vector<city_t> leaf, path;

      usize degree_sum = 0;
      for (const auto& e : city) {
        if (e.d == 1) {
          leaf.push_back(e);
        }
        else {
          path.push_back(e);
        }
        degree_sum += e.d;
      }
      if (degree_sum < 2 * n - 2) {
        std::cout << "-1" << std::endl;
        continue;
      }
      i64 ans = path.back().p - path.front().p;
      const usize pn = path.size();
      const usize ln = leaf.size();
      for (const auto i : rep(1, pn)) {
        path[i - 1].d -= 1;
        path[i].d -= 1;
      }
      std::vector<i64> dp(ln + 1, Inf);
      dp[0] = 0;
      const auto min = [](const i64 l, const i64 r) { return std::min(l, r); };
      for (const auto& e : path) {
        nimi::queue_aggregation<i64, decltype(min)> que(min);
        i64 dsum = 0;
        for (const auto i : rep(0, ln + 1)) {
          if (i != 0) {
            dsum += std::abs(e.p - leaf[i - 1].p);
          }
          if (que.size() > e.d) {
            que.pop();
          }
          que.push(dp[i] - dsum);
          dp[i] = dsum + que.fold_all();
        }
      }
      std::cout << ans + dp[ln] << std::endl;
    }
  }

} // namespace n91

int main() {
  n91::main_();
  return 0;
}
accuracy: 1
time_ms: 790
memory_kb: 3152
final_rank: 8

code_snippet: #include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}

//INSERT ABOVE HERE
template<typename T,typename U>
void sort_pair(vector<T> &ts, vector<U> &us){
  assert(ts.size()==us.size());
  using P = pair<T, U>;
  vector<P> vp;
  for(size_t i=0;i<ts.size();i++)
    vp.emplace_back(ts[i],us[i]);
  sort(vp.begin(),vp.end());
  for(size_t i=0;i<ts.size();i++)
    tie(ts[i],us[i])=vp[i];
}

signed main(){
  Int n;
  while(cin>>n,n){
    vector<Int> ps,ds,qs;
    for(Int i=0;i<n;i++){
      Int p,d;
      cin>>p>>d;
      if(d==1){
        qs.emplace_back(p);
        continue;
      }
      ps.emplace_back(p);
      ds.emplace_back(d);
    }
    sort(qs.begin(),qs.end());
    sort_pair(ps,ds);
    
    if(ps.empty()&&n==2){        
      cout<<qs.back()-qs.front()<<endl;    
      continue;
    }
    
    Int ans=0;    
    for(Int i=0;i+1<(Int)ps.size();i++){
      ans+=ps[i+1]-ps[i];
      ds[i]--;
      ds[i+1]--;
    }
    
    vector<Int> as;
    for(Int i=0;i<(Int)ps.size();i++)
      for(Int j=0;j<ds[i];j++)     
        as.emplace_back(ps[i]);

    assert(is_sorted(as.begin(),as.end()));
    if(as.size()<qs.size()){
      cout<<-1<<endl;
      continue;
    }
    
    const Int INF = 1e16;
    vector<Int> dp(as.size(),INF);
    vector<Int> nx(as.size(),INF);
    for(Int i=0;i<(Int)qs.size();i++){      
      Int idx=lower_bound(as.begin(),as.end(),qs[i])-as.begin();
      Int res=INF*(i!=0);       

      if(i!=0){
        Int idy=lower_bound(as.begin(),as.end(),qs[i-1])-as.begin();
        for(Int j=idy-(n+10);j<=idy+(n+10);j++){
          if(j<0||j>=(Int)as.size()) continue;
          if(j<idx-(n+10)) chmin(res,dp[j]);  
        }
      }
      {
        for(Int j=idx-(n+10);j<=idx+(n+10);j++){
          if(j<0||j>=(Int)as.size()) continue;
          chmin(nx[j],res+abs(as[j]-qs[i]));
          chmin(res,dp[j]);
        }
      }
      if(i!=0){
        Int idy=lower_bound(as.begin(),as.end(),qs[i-1])-as.begin();
        for(Int j=idy-(n+10);j<=idy+(n+10);j++){
          if(j<0||j>=(Int)as.size()) continue;
          dp[j]=INF;
        }
      }
      { 
        for(Int j=idx-(n+10);j<=idx+(n+10);j++){
          if(j<0||j>=(Int)as.size()) continue;
          dp[j]=nx[j];
          nx[j]=INF;          
        }
      }
    }
    if(!qs.empty())
      ans+=*min_element(dp.begin(),dp.end());
    cout<<ans<<endl;
  }
  return 0;
}
accuracy: 1
time_ms: 3410
memory_kb: 410480
final_rank: 20

code_snippet: #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;
}
accuracy: 1
time_ms: 1440
memory_kb: 3100
final_rank: 11

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 99999999999999999
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define NUM 4005

struct Info{
	Info(){
		P = D = 0;
	}
	Info(ll arg_P,ll arg_D){
		P = arg_P;
		D = arg_D;
	}
	bool operator<(const struct Info &arg) const{
		return P < arg.P;
	}
	ll P,D;
};

int N;
ll LEFT[NUM],RIGHT[NUM];
ll dp[NUM];
Info info[2];
vector<Info> Over2,One;
vector<ll> A,B;

void func(){

	Over2.clear();
	One.clear();

	ll tmp_P,tmp_D;

	for(int loop = 0; loop < N; loop++){

		scanf("%lld %lld",&tmp_P,&tmp_D);
		if(loop < 2){
			info[loop].P = tmp_P;
		}

		if(tmp_D == 1){

			One.push_back(Info(tmp_P,tmp_D));

		}else{

			Over2.push_back(Info(tmp_P,tmp_D));
		}
	}

	if(N == 2){

		printf("%lld\n",abs(info[0].P-info[1].P));
		return;
	}

	sort(One.begin(),One.end());
	sort(Over2.begin(),Over2.end());

	for(int i = 0; i < Over2.size(); i++){

		if(i-1 >= 0){

			Over2[i].D--;
		}
		if(i+1 < Over2.size()){

			Over2[i].D--;
		}
	}

	A.clear();
	B.clear();

	for(int i = 0; i < Over2.size(); i++){
		for(int k = 0; k < Over2[i].D; k++){
			A.push_back(Over2[i].P);
		}
	}

	if(A.size() < One.size()){

		printf("-1\n");
		return;
	}

	for(int i = 0; i < One.size(); i++){

		B.push_back(One[i].P);
	}

	ll num_A = A.size();
	ll num_B = B.size();

	ll minimum,min_index,left,right,mid,loc;

	for(int i = 0; i < One.size(); i++){

		minimum = HUGE_NUM;
		for(int k = 0; k < Over2.size(); k++){
			if(Over2[k].D == 0)continue;

			if(minimum > abs(One[i].P-Over2[k].P)){

				minimum = abs(One[i].P-Over2[k].P);
				min_index = k;
			}
		}

		left = 0,right = num_A-1,mid = (left+right)/2;

		while(left <= right){

			if(A[mid] >= Over2[min_index].P){

				loc = mid;
				right = mid-1;
			}else{

				left = mid+1;
			}
			mid = (left+right)/2;
		}

		LEFT[i] = max(0ll,loc-num_B);
		RIGHT[i] = min(num_A-1,loc+num_B);
	}

	dp[0] = 0;
	for(int i = 1; i <= num_B; i++){

		dp[i] = HUGE_NUM;
	}

	left = 0,right = 0;

	for(int i = 0; i < num_A; i++){

		while(left < num_B && RIGHT[left] < i)left++;
		while(right < num_B && LEFT[right] < i)right++;

		for(int k = right; k >= left; k--){
			if(k >= num_B)continue;
			dp[k+1] = min(dp[k+1],dp[k]+abs(A[i]-B[k]));
		}
	}

	printf("%lld\n",dp[num_B]+Over2[Over2.size()-1].P-Over2[0].P);
}

int main(){

	while(true){

		scanf("%d",&N);
		if(N == 0)break;

		func();
	}

	return 0;
}
accuracy: 1
time_ms: 980
memory_kb: 134212
final_rank: 13

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

typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;

#define fi first
#define se second
#define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rep(i,n) repl(i,0,n)
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define mmax(x,y) (x>y?x:y)
#define mmin(x,y) (x<y?x:y)
#define maxch(x,y) x=mmax(x,y)
#define minch(x,y) x=mmin(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt __builtin_popcountll

#define INF 1e16
#define mod 1000000007

struct RangeMinQuery{
  ll dat[(1<<13)-1];
  int size;

  void init(int n_){
    size=1;
    while(size<n_) size*=2;
    for(int i=0;i<2*size-1;i++)dat[i]=INF;
  }

  void update(int k,ll a){
    k+=size-1;
    dat[k]=a;
    while(k>0){
      k=(k-1)/2;
      dat[k]=min(dat[k*2+1],dat[k*2+2]);
    }
  }

  ll subquery(int a,int b,int k,int l,int r){
    if(r<=a||b<=l)return INF;
    if(a<=l&&r<=b)return dat[k];
    else{
      return min(subquery(a,b,k*2+1,l,(l+r)/2),subquery(a,b,k*2+2,(l+r)/2,r));
    }
  }
  
  ll query(int a,int b){
    return subquery(a,b,0,0,size);
  }
};

ll N;
ll p[4001],d[4001];
ll dp[2][4001];
RangeMinQuery sgt;

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

  while(1){
    cin>>N;
    if(N==0)break;
    ll dsum=0;
    rep(i,N){
      cin>>p[i]>>d[i];
      dsum+=d[i];
    }
    if(dsum<2*(N-1)){
      cout<<-1<<endl;
      continue;
    }
    vector<P> vs0;
    vector<ll> vs1;
    rep(i,N){
      if(d[i]>1){
        vs0.push_back(P(p[i],d[i]));
      }else vs1.push_back(p[i]);
    }
    sort(all(vs0)); sort(all(vs1));
    ll crt=0,nxt=1;
    ll n0=vs0.size(),n1=vs1.size();
    ll res=0;
    if(n0>1){
      rep(i,n0){
        if(i==0||i==n0-1) vs0[i].se-=1;
        else vs0[i].se-=2;
      }
    }
    if(n0==0&&n1==2){
      cout<<vs1[1]-vs1[0]<<endl;
      continue;
    }
    rep(i,n0-1)res+=vs0[i+1].fi-vs0[i].fi;
    rep(i,2)rep(j,n1+1)dp[i][j]=INF;
    dp[crt][0]=0;
    rep(i,n0){
      sgt.init(n1+1);
      ll sum=0;
      rep(j,n1+1){
        sgt.update(j,dp[crt][j]-sum);
        dp[nxt][j]=sgt.query(j-vs0[i].se,j+1)+sum;
        if(j<n1)sum+=llabs(vs0[i].fi-vs1[j]);
      }
      swap(crt,nxt);
    }
    cout<<res+dp[crt][n1]<<endl;
  }

  return 0;
}
accuracy: 1
time_ms: 4800
memory_kb: 3424
final_rank: 17

code_snippet: #include <bits/stdc++.h>
#define INF 1LL<<60
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef pair<P,int> PP;

ll labs(ll v){
	if(v<0LL)return -v;
	return v;
}

int n;
ll dp[4001][4001];
vector<ll> d1;
vector<P> vec;

void solve(){
	d1.clear();
	vec.clear();
	ll sum=2;
	for(int i=0;i<n;i++){
		int p,d;
		scanf("%d%d",&p,&d);
		sum+=d-2;
		if(d==1){
			d1.push_back(p);
		}else{
			vec.push_back(P(p,d));
		}
	}
	sort(d1.begin(),d1.end());
	sort(vec.begin(),vec.end());
	if(sum<0){
		printf("-1\n");
		return;
	}
	if(vec.size()==0){
		printf("%lld\n",d1[1]-d1[0]);
		return;
	}
	for(int i=0;i<=d1.size();i++){
		dp[0][i]=INF;
	}
	dp[0][0]=0;
	for(int i=0;i<vec.size();i++){
		//cout << vec[i].first << " "<< vec[i].second << endl;
		int rest=vec[i].second-2;
		if(i==0){
			rest++;
		}
		if(i+1==vec.size()){
			rest++;
		}
		for(int j=0;j<=d1.size();j++){
			dp[i+1][j]=dp[i][j];
		}
		deque<PP> deq;
		ll lazysum=0;
		for(int j=0;j<d1.size();j++){
			if(rest==0)break;
			while(deq.size()>0 && deq[0].second<j+1-rest){
				deq.pop_front();
			}
			while(deq.size()>0 && deq.back().first.first+lazysum-deq.back().first.second>=dp[i][j]){
				deq.pop_back();
			}
			deq.push_back(PP(P(dp[i][j],lazysum),j));
			lazysum+=labs(d1[j]-vec[i].first);
			dp[i+1][j+1]=min(dp[i+1][j+1],deq[0].first.first+lazysum-deq[0].first.second);
		}
	}
	/*
	for(int i=0;i<=vec.size();i++){
		for(int j=0;j<=d1.size();j++){
			printf("%lld ",dp[i][j]);
		}
		printf("\n");
	}
	*/
	printf("%lld\n",dp[vec.size()][d1.size()]+vec[vec.size()-1].first-vec[0].first);
}

int main(void){
	while(1){
		scanf("%d",&n);
		if(n==0)break;
		solve();
	}
	return 0;
}
accuracy: 1
time_ms: 640
memory_kb: 73800
final_rank: 12

code_snippet: #define _USE_MATH_DEFINES
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <cfloat>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <time.h>
#include <vector>
#include <random>
#include <cassert>
using namespace std;

#define rep(i, N) for (int i = 0; i < N; i++)
#define pb push_back

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> i_i;
typedef pair<ll, int> ll_i;
typedef pair<int, ll> i_ll;
typedef pair<double, int> d_i;
typedef pair<ll, ll> ll_ll;
typedef pair<double, double> d_d;
typedef vector<int> vi;
struct edge { int v; ll w; };

ll _MOD = 1000000009;
double EPS = 1e-10;
ll INF = LLONG_MAX / 2;

int main() {
	for (;;) {
		int n; cin >> n;
		if (!n) break;
		vector<int> a(n), b(n);
		rep(u, n) scanf("%d%d", &a[u], &b[u]);
		if (n == 2) {
			cout << abs(a[0] - a[1]) << endl;
			continue;
		}
		vector<i_i> ab;
		vector<int> c;
		rep(u, n)
			if (b[u] == 1) c.pb(a[u]);
			else ab.pb(i_i(a[u], b[u] - 2));
		int N = ab.size(), M = c.size();
		if (!N) {
			cout << -1 << endl;
			continue;
		}
		sort(ab.begin(), ab.end());
		ab.front().second++;
		ab.back().second++;
		sort(c.begin(), c.end());
		vector<ll> dp(M + 1, INF);
		dp[0] = 0;
		rep(i, N) {
			int a = ab[i].first, b = ab[i].second;
			vector<ll> _dp(M + 1, INF);
			deque<i_ll> d;
			ll sum = 0;
			rep(j, M + 1) {
				if (!d.empty() && j - d.front().first > b) d.pop_front();
				while (!d.empty() && d.back().second >= dp[j] - sum) d.pop_back();
				d.push_back(i_ll(j, dp[j] - sum));
				if (!d.empty()) _dp[j] = d.front().second + sum;
				if (j < M) sum += abs(c[j] - a);
			}
			dp = _dp;
		}
		ll ans = dp[M] + ab.back().first - ab.front().first;
		if (ans >= INF) ans = -1;
		cout << ans << endl;
	}
}
accuracy: 1
time_ms: 570
memory_kb: 3324
final_rank: 6

code_snippet: #include <bits/stdc++.h>

using namespace std;

typedef long long int64;
const int64 INF = 1LL << 58;

int64 MinimumCost(vector< int > &A, vector< int > &B)
{
  vector< int > near(B.size());
  int tail = 0;
  for(int i = 0; i < B.size(); i++) {
    while(tail < A.size() && A[tail] < B[i]) ++tail;
    near[i] = tail;
  }
  int sz = (int) B.size() * 2 + 1;
  vector< int64 > dp(sz, 0);
  for(int i = 0; i < B.size(); i++) {
    const int diff = near[i] - (i == 0 ? 0 : near[i - 1]);
    for(int j = 0; j < sz; j++) dp[j] = dp[min(j + diff, sz - 1)];
    vector< int64 > nxt(sz, INF);
    for(int j = 0; j < sz - 1; j++) {
      const int k = near[i] - (int) B.size() + j;
      nxt[j + 1] = min(nxt[j + 1], nxt[j]);
      if(k < 0 || k >= A.size()) continue;
      nxt[j + 1] = min(nxt[j + 1], dp[j] + abs(B[i] - A[k]));
    }
    dp.swap(nxt);
  }
  if(dp.back() == INF) return (-1);
  return (dp.back());
}

int main()
{
  int N, P[4000], D[4000];

  while(scanf("%d", &N), N) {
    if(N == 2) {
      int a, b, c, d;
      scanf("%d %d %d %d", &a, &b, &c, &d);
      printf("%d\n", abs(a - c));
      continue;
    }
    vector< int > latte, malta;
    for(int i = 0; i < N; i++) {
      scanf("%d %d", &P[i], &D[i]);
      if(D[i] == 1) latte.push_back(i);
      else malta.push_back(i);
    }

    sort(begin(latte), end(latte), [&](int a, int b) -> bool
    {
      return (P[a] < P[b]);
    });
    sort(begin(malta), end(malta), [&](int a, int b) -> bool
    {
      return (P[a] < P[b]);
    });

    for(int i = 1; i < malta.size(); i++) --D[malta[i]];
    for(int i = 0; i + 1 < malta.size(); i++) --D[malta[i]];

    vector< int > beet, vs;
    for(int i : malta) while(D[i]--) beet.push_back(P[i]);
    for(int i : latte) vs.push_back(P[i]);
    if(vs.size() > beet.size()) puts("-1");
    else printf("%lld\n", MinimumCost(beet, vs) + P[malta.back()] - P[malta.front()]);
  }
}
accuracy: 1
time_ms: 2360
memory_kb: 68752
final_rank: 14

code_snippet: #include <bits/stdc++.h>

using namespace std;

typedef long long int64;
const int64 INF = 1LL << 58;

int64 MinimumCost(vector< int > &A, vector< int > &B)
{
  vector< int > near(B.size());
  int tail = 0;
  for(int i = 0; i < B.size(); i++) {
    while(tail < A.size() && A[tail] < B[i]) ++tail;
    near[i] = tail;
  }
  int sz = (int) B.size() * 2 + 1;
  vector< int64 > dp(sz, 0);
  for(int i = 0; i < B.size(); i++) {
    const int diff = near[i] - (i == 0 ? 0 : near[i - 1]);
    for(int j = 0; j < sz; j++) dp[j] = dp[min(j + diff, sz - 1)];
    vector< int64 > nxt(sz, INF);
    for(int j = 0; j < sz - 1; j++) {
      const int k = near[i] - (int) B.size() + j;
      nxt[j + 1] = min(nxt[j + 1], nxt[j]);
      if(k < 0 || k >= A.size()) continue;
      nxt[j + 1] = min(nxt[j + 1], dp[j] + abs(B[i] - A[k]));
    }
    dp.swap(nxt);
  }
  if(dp.back() == INF) return (-1);
  return (dp.back());
}

int main()
{
  int N, P[4000], D[4000];

  while(scanf("%d", &N), N) {
    if(N == 2) {
      int a, b, c, d;
      cin >> a >> b >> c >> d;
      cout << abs(a - c) << endl;
      continue;
    }
    vector< int > latte, malta;
    for(int i = 0; i < N; i++) {
      scanf("%d %d", &P[i], &D[i]);
      if(D[i] == 1) latte.push_back(i);
      else malta.push_back(i);
    }

    sort(begin(latte), end(latte), [&](int a, int b) -> bool
    {
      return (P[a] < P[b]);
    });
    sort(begin(malta), end(malta), [&](int a, int b) -> bool
    {
      return (P[a] < P[b]);
    });

    for(int i = 1; i < malta.size(); i++) --D[malta[i]];
    for(int i = 0; i + 1 < malta.size(); i++) --D[malta[i]];

    vector< int > beet, vs;
    for(int i : malta) while(D[i]--) beet.push_back(P[i]);
    for(int i : latte) vs.push_back(P[i]);
    if(vs.size() > beet.size()) puts("-1");
    else printf("%lld\n", MinimumCost(beet, vs) + P[malta.back()] - P[malta.front()]);
  }
}
accuracy: 1
time_ms: 2380
memory_kb: 68644
final_rank: 15

code_snippet: #include <bits/stdc++.h>

using namespace std;

typedef long long int64;
const int64 INF = 1LL << 58;

int64 MinimumCost(vector< int > &A, vector< int > &B)
{
  vector< int > near(B.size());
  int tail = 0;
  for(int i = 0; i < B.size(); i++) {
    while(tail < A.size() && A[tail] < B[i]) ++tail;
    near[i] = tail;
  }
  int sz = (int) B.size() * 2 + 1;
  vector< int64 > dp(sz, 0);
  for(int i = 0; i < B.size(); i++) {
    const int diff = near[i] - (i == 0 ? 0 : near[i - 1]);
    for(int j = 0; j < sz; j++) dp[j] = dp[min(j + diff, sz - 1)];
    vector< int64 > nxt(sz, INF);
    for(int j = 0; j < sz - 1; j++) {
      const int k = near[i] - (int) B.size() + j;
      nxt[j + 1] = min(nxt[j + 1], nxt[j]);
      if(k < 0 || k >= A.size()) continue;
      nxt[j + 1] = min(nxt[j + 1], dp[j] + abs(B[i] - A[k]));
    }
    dp.swap(nxt);
  }
  if(dp.back() == INF) return (-1);
  return (dp.back());
}

int main()
{
  int N, P[4000], D[4000];

  while(scanf("%d", &N), N) {
    if(N == 2) {
      int a, b, c, d;
      cin >> a >> b >> c >> d;
      cout << abs(a - c) << endl;
      continue;
    }
    vector< int > latte, malta;
    for(int i = 0; i < N; i++) {
      scanf("%d %d", &P[i], &D[i]);
      if(D[i] == 1) latte.push_back(i);
      else malta.push_back(i);
    }

    sort(begin(latte), end(latte), [&](int a, int b) -> bool
    {
      return (P[a] < P[b]);
    });
    sort(begin(malta), end(malta), [&](int a, int b) -> bool
    {
      return (P[a] < P[b]);
    });

    for(int i = 1; i < malta.size(); i++) --D[malta[i]];
    for(int i = 0; i + 1 < malta.size(); i++) --D[malta[i]];

    vector< int > beet, vs;
    for(int i : malta) while(D[i]--) beet.push_back(P[i]);
    for(int i : latte) vs.push_back(P[i]);
    auto get = MinimumCost(beet, vs);
    if(get == -1) puts("-1");
    else printf("%lld\n", get + P[malta.back()] - P[malta.front()]);
  }
}
accuracy: 1
time_ms: 2640
memory_kb: 68652
final_rank: 16