Problem:
問題 D : TiMe Table
問題文
ある学生は朝にいつも乗る通学バスで，あることに気がついた．
そのバスの利用者がいつも同じなのだ．
気になってバスに乗っている利用者たちに聞いてみると，毎日決まった時刻にバス停に来ているようである．
それなら，乗客にとってもっとよいバスの時間割があるのではないかとその学生は考えた．
学生の乗る通学路には，バスの営業所から終点までに
s
個のバス停が一直線に並んでいる．(営業所はバス停には含まれないが，終点はバス停に含まれる．)
各バス停には，営業所から近い方から順に
1
から
s
までの番号が付けられている．
営業所と
i
番目のバス停の距離は
x_i
である．
バスはまず営業所を出発し，それから
x_i
経った後に
i
番目のバス停に到着する．
バス停には
n
人の利用者がやって来る．
i
番目の利用者は時刻
t_i
にバス停
p_i
にやって来る．
この通学路には1日にちょうど
m
本のバスが営業所から終点まで走ることになっている．
バスはバス停に止まると，そのバス停で待っていた利用者を全員回収して，次のバス停に向かう．
バス停で利用者を回収する時間は無視出来ると仮定する．
いま各バスが営業所から出発する時刻を自由に決めることができるとき，利用者の待ち時間の和を最小化しよう．
入力形式
入力は以下の形式で与えられる．
s
n
m
x_1
...
x_s
t_1
p_1
...
t_n
p_n
出力形式
待ち時間の和の最小値を一行に出力せよ．
制約
1 ≤ s,   n,   m ≤ 2000
1 ≤ x_1 < x_2 < …< x_s ≤ 10^4
0 ≤ t_i ≤ 10^4
1 ≤ p_i ≤ s
入力値はすべて整数である.
入出力例
入力例 1
2 2 1
1 5
0 1
0 2
出力例 1
4
入力例 2
2 3 2
1 15
0 1
5 1
5 2
出力例 2
5
この例では，バスを時刻
−10
と
4
に出発させることが最適である．
入力例 3
4 8 1
6 38 105 390
14 1
4 2
39 3
89 2
32 4
1 1
25 1
60 4
出力例 3
1123

Submitted solutions:

code_snippet: // QCFium 法
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")


#ifndef HIDDEN_IN_VS // 折りたたみ用

// 警告の抑制
#define _CRT_SECURE_NO_WARNINGS

// ライブラリの読み込み
#include <bits/stdc++.h>
using namespace std;

// 型名の短縮
using ll = long long; using ull = unsigned long long; // -2^63 ～ 2^63 = 9e18（int は -2^31 ～ 2^31 = 2e9）
using pii = pair<int, int>;	using pll = pair<ll, ll>;	using pil = pair<int, ll>;	using pli = pair<ll, int>;
using vi = vector<int>;		using vvi = vector<vi>;		using vvvi = vector<vvi>;	using vvvvi = vector<vvvi>;
using vl = vector<ll>;		using vvl = vector<vl>;		using vvvl = vector<vvl>;	using vvvvl = vector<vvvl>;
using vb = vector<bool>;	using vvb = vector<vb>;		using vvvb = vector<vvb>;
using vc = vector<char>;	using vvc = vector<vc>;		using vvvc = vector<vvc>;
using vd = vector<double>;	using vvd = vector<vd>;		using vvvd = vector<vvd>;
template <class T> using priority_queue_rev = priority_queue<T, vector<T>, greater<T>>;
using Graph = vvi;

// 定数の定義
const double PI = acos(-1);
int DX[4] = { 1, 0, -1, 0 }; // 4 近傍（下，右，上，左）
int DY[4] = { 0, 1, 0, -1 };
int INF = 1001001001; ll INFL = 4004004003094073385LL; // (int)INFL = INF, (int)(-INFL) = -INF;

// 入出力高速化
struct fast_io { fast_io() { cin.tie(nullptr); ios::sync_with_stdio(false); cout << fixed << setprecision(18); } } fastIOtmp;

// 汎用マクロの定義
#define all(a) (a).begin(), (a).end()
#define sz(x) ((int)(x).size())
#define lbpos(a, x) (int)distance((a).begin(), std::lower_bound(all(a), (x)))
#define ubpos(a, x) (int)distance((a).begin(), std::upper_bound(all(a), (x)))
#define Yes(b) {cout << ((b) ? "Yes\n" : "No\n");}
#define rep(i, n) for(int i = 0, i##_len = int(n); i < i##_len; ++i) // 0 から n-1 まで昇順
#define repi(i, s, t) for(int i = int(s), i##_end = int(t); i <= i##_end; ++i) // s から t まで昇順
#define repir(i, s, t) for(int i = int(s), i##_end = int(t); i >= i##_end; --i) // s から t まで降順
#define repe(v, a) for(const auto& v : (a)) // a の全要素（変更不可能）
#define repea(v, a) for(auto& v : (a)) // a の全要素（変更可能）
#define repb(set, d) for(int set = 0, set##_ub = 1 << int(d); set < set##_ub; ++set) // d ビット全探索（昇順）
#define repis(i, set) for(int i = lsb(set), bset##i = set; i < 32; bset##i -= 1 << i, i = lsb(bset##i)) // set の全要素（昇順）
#define repp(a) sort(all(a)); for(bool a##_perm = true; a##_perm; a##_perm = next_permutation(all(a))) // a の順列全て（昇順）
#define uniq(a) {sort(all(a)); (a).erase(unique(all(a)), (a).end());} // 重複除去
#define EXIT(a) {cout << (a) << endl; exit(0);} // 強制終了
#define inQ(x, y, u, l, d, r) ((u) <= (x) && (l) <= (y) && (x) < (d) && (y) < (r)) // 半開矩形内判定

// 汎用関数の定義
template <class T> inline ll powi(T n, int k) { ll v = 1; rep(i, k) v *= n; return v; }
template <class T> inline bool chmax(T& M, const T& x) { if (M < x) { M = x; return true; } return false; } // 最大値を更新（更新されたら true を返す）
template <class T> inline bool chmin(T& m, const T& x) { if (m > x) { m = x; return true; } return false; } // 最小値を更新（更新されたら true を返す）
template <class T> inline T getb(T set, int i) { return (set >> i) & T(1); }
template <class T> inline T smod(T n, T m) { n %= m; if (n < 0) n += m; return n; } // 非負mod

// 演算子オーバーロード
template <class T, class U> inline istream& operator>>(istream& is, pair<T, U>& p) { is >> p.first >> p.second; return is; }
template <class T> inline istream& operator>>(istream& is, vector<T>& v) { repea(x, v) is >> x; return is; }
template <class T> inline vector<T>& operator--(vector<T>& v) { repea(x, v) --x; return v; }
template <class T> inline vector<T>& operator++(vector<T>& v) { repea(x, v) ++x; return v; }

#endif // 折りたたみ用


#if __has_include(<atcoder/all>)
#include <atcoder/all>
using namespace atcoder;

#ifdef _MSC_VER
#include "localACL.hpp"
#endif

//using mint = modint1000000007;
using mint = modint998244353;
//using mint = static_modint<1000000000>;
//using mint = modint; // mint::set_mod(m);

namespace atcoder {
	inline istream& operator>>(istream& is, mint& x) { ll x_; is >> x_; x = x_; return is; }
	inline ostream& operator<<(ostream& os, const mint& x) { os << x.val(); return os; }
}
using vm = vector<mint>; using vvm = vector<vm>; using vvvm = vector<vvm>; using vvvvm = vector<vvvm>; using pim = pair<int, mint>;
#endif


#ifdef _MSC_VER // 手元環境（Visual Studio）
#include "local.hpp"
#else // 提出用（gcc）
inline int popcount(int n) { return __builtin_popcount(n); }
inline int popcount(ll n) { return __builtin_popcountll(n); }
inline int lsb(int n) { return n != 0 ? __builtin_ctz(n) : 32; }
inline int lsb(ll n) { return n != 0 ? __builtin_ctzll(n) : 64; }
template <size_t N> inline int lsb(const bitset<N>& b) { return b._Find_first(); }
inline int msb(int n) { return n != 0 ? (31 - __builtin_clz(n)) : -1; }
inline int msb(ll n) { return n != 0 ? (63 - __builtin_clzll(n)) : -1; }
#define dump(...)
#define dumpel(...)
#define dump_list(v)
#define dump_mat(v)
#define input_from_file(f)
#define output_to_file(f)
#define Assert(b) { if (!(b)) { vc MLE(1<<30); EXIT(MLE.back()); } } // RE の代わりに MLE を出す
#endif


//【Monge DAG 最短路（長さごと，関数）】O(K n log n)（の改変）
/*
* 重み付き DAG G を
*	頂点集合が [0..n]
*	辺 s→t（s<t）の重みが n+1 次狭義上三角 Monge 行列の成分 M(s,t)
* と定める．各 k∈[0..K], i∈[0..n] について，
* 頂点 0 から i への長さ k のパスの重みの最小値を格納した二次元リストを返す．
*/
template <class T, class FUNC>
T monge_DAG_shortest_path_all(int K, int n, const FUNC& M) {
	//【方法】
	//		dp[k][i] : 頂点 0 から i までの長さ k のパスの重みの最小値
	// と定めると，遷移は
	//		dp[k+1][t] = MIN_s∈[0..t) (dp[k][s] + M(s,t))
	// となる．これは min-plus 代数における行列ベクトル積として
	//		dp[k+1] = M^T * dp[k]
	// と表される．
	// 
	// k を固定する．
	// M^T は下三角 Monge なのでその第 s 列に dp[k][s] を加えた行列も下三角 Monge である．
	// よって monotone minima で行最小値を求めることができる．

	// dp[k][i] : 頂点 0 から i までの長さ k のパスの重みの最小値
	vector<T> dp(n + 1, T(INFL));
	dp[0] = 0;

	T NIL = (T)(INFL + (1LL << 61) + 100);

	rep(k, K) {
		vector<T> ndp(n + 1, T(INFL));

		// monotone minima
		vi j_min(n + 1);
		for (int di = 1 << msb(n + 1); di > 0; di >>= 1) {
			int di2 = 2 * di;
			for (int i = di; i <= n + 1; i += di2) {
				int jL = (i - di > 0 ? j_min[i - di - 1] : 0);
				int jR = (i + di <= n + 1 ? j_min[i + di - 1] : n);
				chmin(jR, i - 1);

				T a_min = T(INFL);
				repi(j, jL, jR) {
					T val = M(j, i - 1) + dp[j];

					if (chmin(a_min, val)) j_min[i - 1] = j;
				}
			}
		}

		repi(t, k + 1, n) ndp[t] = M(j_min[t], t) + dp[j_min[t]];

		dp = move(ndp);
	}

	return dp[n];

	/* M の定義の雛形
	auto M = [&](int i, int j) {
		return 0LL;
	};
	*/
}


//【Monge 性判定】O(h w)
/*
* 行列 A[0..h)[0..w) が Monge かを返す．NIL は無効値を表す．
*
* 制約：無効値は右上または左下にしか存在しない．
*/
template <class FUNC>
bool mongeQ(int h, int w, const FUNC& A, ll NIL = 2 * INFL + 100) {
	// verify : https://atcoder.jp/contests/abc224/tasks/abc224_b

	vvl a(h, vl(w));
	rep(i, h) rep(j, w) a[i][j] = A(i, j);

	rep(i, h - 1) rep(j, w - 1) {
		// 左上や右下に無効値があったら Monge ではない．
		if (a[i][j] == NIL || a[i + 1][j + 1] == NIL) {
			if (a[i + 1][j] != NIL && a[i][j + 1] != NIL) return false;
			continue;
		}

		// 右上や左下に無効値があったら無視する．
		if (a[i + 1][j] == NIL || a[i][j + 1] == NIL) continue;

		if (a[i][j] + a[i + 1][j + 1] > a[i][j + 1] + a[i + 1][j]) return false;
	}
	return true;

	/* A の定義の雛形
	auto A = [&](int i, int j) {
		return a[i][j];
	};
	*/
}


int main() {
//	input_from_file("input.txt");
//	output_to_file("output.txt");

	dump(INFL = 999);

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

	vi x(s);
	cin >> x;

	vi t(n), p(n);
	rep(i, n) cin >> t[i] >> p[i];
	--p;

	rep(i, n) t[i] -= x[p[i]];

	int t_min = *min_element(all(t));
	rep(i, n) t[i] -= t_min - 1;
	dump(t);

	int T = *max_element(all(t));
	dump("T:", T);

	vi cnt(T + 1); vl cnt1(T + 1);
	rep(i, n) {
		cnt[t[i]]++;
		cnt1[t[i]] += t[i];
	}
	dump(cnt); dump(cnt1);

	vi acc(T + 2); vl acc1(T + 2);
	rep(t, T + 1) {
		acc[t + 1] = acc[t] + cnt[t];
		acc1[t + 1] = acc1[t] + cnt1[t];
	}

	auto M = [&](int i, int j) {
		return (acc[T - i] - acc[T - j + 1]) * (T - i) - (acc1[T - i] - acc1[T - j + 1]);
	};
//	repi(i, 0, T) repi(j, 0, T) cout << M(i, j) << " \n"[j == T];
	dump("Monge? :", mongeQ(T + 1, T + 1, M));

	EXIT(monge_DAG_shortest_path_all<ll>(m, T, M));
}
accuracy: 1
time_ms: 580
memory_kb: 4072
final_rank: 14

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

ll S,N,M;
vector<ll> X,T,ST;
vector<vector<ll>> DP;

ll f_i(int n,int i,int d){
    if(n<=i)return 1e18;
    return DP[i][d-1]+T[n-1]*(n-i)-(ST[n]-ST[i]);
}
void Monotone_Minima(ll left,ll right,ll up,ll down,int d){
    ll mid=(up+down)/2;
    ll mi=1e18,id=left;
    for(ll w=left;w<right;w++){
        ll nxt=f_i(mid,w,d);
        if(nxt<mi)id=w,mi=nxt;
    }
    DP[mid][d]=mi;
    if(mid-up>0)Monotone_Minima(left,id+1,up,mid,d);
    if(down-mid>1)Monotone_Minima(id,right,mid+1,down,d);
}

int main() {
    cin>>S>>N>>M;
    X.resize(S);
    T.resize(N);
    for(int i=0;i<S;i++)cin>>X[i];
    for(int i=0;i<N;i++){
        int t,p;
        cin>>t>>p;
        T[i]=t-X[p-1];
    }
    if(N<=M){
        cout<<0<<endl;
        return 0;
    }
    sort(T.begin(),T.end());
    ST.assign(N+1,0);
    for(int i=0;i<N;i++)ST[i+1]=ST[i]+T[i];
    DP.assign(N+1,vector<ll>(M+1,1e18));
    DP[0][0]=0;
    for(ll d=1;d<=M;d++)Monotone_Minima(0,N+1,0,N+1,d);
    cout<<DP[N][M]<<endl;
}
accuracy: 1
time_ms: 60
memory_kb: 17964
final_rank: 9

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

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

ll S,N,M;
vector<ll> X,T,ST;
vector<vector<ll>> DP;


//f_i(x) O(log(M))
ll f_i(int n,int i,int d){
    // if(n<=d)return 0;
    if(n<=i)return 1e18;
    ll res=DP[i][d-1]+T[n-1]*(n-i)-(ST[n]-ST[i]);
    return res;
}


void Monotone_Minima(ll left,ll right,ll up,ll down,int d){
    ll mid=(up+down)/2;
    ll mi=1e18;
    ll id=left;
    for(ll w=left;w<right;w++){
        ll nxt=f_i(mid,w,d);
        if(nxt<mi){
            id=w;
            mi=nxt;
        }
    }
    DP[mid][d]=mi;
    if(mid-up>0){
        Monotone_Minima(left,id+1,up,mid,d);
    }
    if(down-mid>1){
        Monotone_Minima(id,right,mid+1,down,d);
    }
}


int main() {
    cin>>S>>N>>M;
    X.resize(S);
    T.resize(N);
    for(int i=0;i<S;i++)cin>>X[i];
    for(int i=0;i<N;i++){
        int t,p;
        cin>>t>>p;
        T[i]=t-X[p-1];
    }
    if(N<=M){
        cout<<0<<endl;
        return 0;
    }
    sort(T.begin(),T.end());
    ST.assign(N+1,0);
    for(int i=0;i<N;i++){
        ST[i+1]=ST[i]+T[i];
    }
    DP.assign(N+1,vector<ll>(M+1,1e18));
    DP[0][0]=0;
    for(ll d=1;d<=M;d++){
        Monotone_Minima(0,N+1,0,N+1,d);
    }
    cout<<DP[N][M]<<endl;
}
accuracy: 1
time_ms: 50
memory_kb: 18092
final_rank: 8

code_snippet: #pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")

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

ll S,N,M;
vector<ll> X,T,ST;
vector<vector<ll>> DP;


//f_i(x) O(log(M))
ll f_i(int n,int i,int d){
    if(n<=d)return 0;
    if(n<=i)return 1e18;
    ll res=DP[i][d-1]+T[n-1]*(n-i)-(ST[n]-ST[i]);
    return res;
}


void Monotone_Minima(ll left,ll right,ll up,ll down,int d){
    ll mid=(up+down)/2;
    ll mi=1e18;
    ll id=left;
    for(ll w=left;w<right;w++){
        ll nxt=f_i(mid,w,d);
        if(nxt<mi){
            id=w;
            mi=nxt;
        }
    }
    DP[mid][d]=mi;
    if(mid-up>0){
        Monotone_Minima(left,id+1,up,mid,d);
    }
    if(down-mid>1){
        Monotone_Minima(id,right,mid+1,down,d);
    }
}


int main() {
    cin>>S>>N>>M;
    X.resize(S);
    T.resize(N);
    for(int i=0;i<S;i++)cin>>X[i];
    for(int i=0;i<N;i++){
        int t,p;
        cin>>t>>p;
        T[i]=t-X[p-1];
    }
    if(N<=M){
        cout<<0<<endl;
        return 0;
    }
    sort(T.begin(),T.end());
    ST.assign(N+1,0);
    for(int i=0;i<N;i++){
        ST[i+1]=ST[i]+T[i];
    }
    DP.assign(N+1,vector<ll>(M+1,1e18));
    DP[0][0]=0;
    for(ll d=1;d<=M;d++){
        Monotone_Minima(0,N+1,0,N+1,d);
    }
    cout<<DP[N][M]<<endl;
}
accuracy: 1
time_ms: 50
memory_kb: 17968
final_rank: 7

code_snippet: #line 1 "SPJ-Library/tests/monge_graph_shortest_path.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2603"
#include <cassert>
#include <iostream>
#include <vector>

#line 1 "SPJ-Library/graph/monge_graph_shortest_path.hpp"
// reference: https://noshi91.github.io/algorithm-encyclopedia/d-edge-shortest-path-monge
// calculate the minimum possible weight of a path from 0 to n-1 with exactly d edges on a complete DAG with Monge-ish weight edges
// problem settings:
// 	- given a graph satisfying the following conditions
//		- vertex set: {0, 1, ..., n-1}  (n >= 1)
// 		- edge set: {(i, j) | 0 <= i < j < n}  (directed)
// 		- Monge-ish weight of the edges: for all 0 <= i < j < k < l < n, c(i, k) + c(j, l) <= c(i, l) + c(j, k)
// 			- this resembles the definition of supermodular set functions
// 	- the task is to compute the shortest path with `d` edges (min{n - 1, 1} <= d < n) from 0 to n-1 on this graph
// time complexity:
// 	- in ordinary case, O(N^2 lg (max_{i, j} abs(c(i, j))))
// 	- when you can compute the shortest path without the constraint of the included edges in T(N) time, the whole complexity is
// 		O(T(N) lg (max_{i, j} abs(c(i, j))))

#line 1 "SPJ-Library/optimization/golden_section_search.hpp"
#include <algorithm>
#include <array>
#line 4 "SPJ-Library/optimization/golden_section_search.hpp"
#include <cmath>
#include <limits>
#include <tuple>

// find the min/aximum value of unimodal function `f` on [x_lb, x_ub), whose type is (F: X -> Y)
// constraints:
//	- X is an integer type (int, long long, __int128_t)
// 	- std::numeric_limits<X>::min() < x_lb < x_ub < std::numeric_limits<X>::max()
//	- (x_ub - x_lb) * 2 < std::numeric_limits<X>::max() - std::numeric_limits<X>::min()
// 	- f is unimodal
//		(i.e. if `find_min`, there exists two integers x_0, x_1 such that the following conditions hold:
// 		- x_lb <= x_0 <= x_1 < x_ub,
//		- for all x \in [x_lb, x_0), 		f(x) > f(x+1),
//		- for all x \in [x_0, x_1), 		f(x) == f(x+1),
//		- for all x \in [x_1, x_ub - 1), 	f(x) < f(x+1),
//		if not `find_min`, vice versa)
// usage:
// 		auto f = [](int x) -> ld { return sinl(ld(x) * pi / ld(180.)); };
// 		auto [x, y] = golden_section_search_int<int, ld, decltype(f)>(f, 57, 100, false); // (90, 1)
template <class X_int, class Y, class F>
std::pair<X_int, Y> golden_section_search_int(const F &f, X_int x_lb, X_int x_ub, bool find_min = true) {
	if(x_lb + 1 == x_ub) return std::make_pair(x_lb, f(x_lb));
	assert(x_lb < x_ub);
	std::array<X_int, 4> xs = {x_lb - 1, x_lb, x_lb + 1, x_lb + 2};
	while(xs.back() < x_ub) {
		xs[1] = xs[2];
		xs[2] = xs[3];
		xs[3] = xs[1] - xs[0] + xs[2];
	}
	auto get = [&f, &find_min](X_int x) -> Y { return find_min ? f(x) : -f(x); };
	Y y1 = get(xs[1]), y2 = get(xs[2]);
	auto right_is_smaller = [&x_ub, &xs, &y1, &y2]() -> bool { return xs[2] < x_ub && y1 > y2; };
	while(xs.back() - xs.front() > 3) {
		if(right_is_smaller()) {
			xs[0] = xs[1];
			xs[1] = xs[2];
			xs[2] = xs[3] - xs[1] + xs[0];
			y1 = y2;
			if(xs[2] < x_ub) y2 = get(xs[2]);
		} else {
			xs[3] = xs[2];
			xs[2] = xs[1];
			xs[1] = xs[3] - xs[2] + xs[0];
			y2 = y1;
			y1 = get(xs[1]);
		}
	}
	return right_is_smaller() ? std::make_pair(xs[2], find_min ? y2 : -y2) : std::make_pair(xs[1], find_min ? y1 : -y1);
};

// find the min/aximum value of unimodal function `f` on [x_min, x_max], whose type is (F: X -> Y)
// returns f(x), where x is in [x* - eps, x* + eps] and x* is the optimal solution
// constraints:
//	- X (= X_float) is a floating point number type (float, double, long double)
// 	- std::numeric_limits<X>::min() < x_min <= x_max
//	- (x_max - x_min) * 2 < std::numeric_limits<X>::max() - std::numeric_limits<X>::min()
// 	- f is unimodal
//		(i.e. if `find_min`, there exists two integers x_0, x_1 such that the following conditions hold:
// 		- x_min <= x_0 <= x_1 <= x_max,
//		- for all x \in (x_min, x_0), 	f'(x) < 0,
//		- for all x \in (x_0, x_1), 	f'(x) == 0,
//		- for all x \in (x_1, x_max), 	f'(x) > 0,
//		if not `find_min`, vice versa)
// usage:
// 		auto f = [](ld x) -> ld { return sinl(x * pi / ld(180.)); };
// 		auto [x, y] = golden_section_search_float<ld, ld, decltype(f)>(f, 57, 100, false); // (90, 1)
template <class X_float, class Y, class F>
std::pair<X_float, Y> golden_section_search_float(const F &f, X_float x_min, X_float x_max, int iteration_number, bool find_min = true) {
	assert(x_min <= x_max);
	constexpr long double phi_inv = 0.6180339887498949L;  // (sqrt(5) - 1) / 2
	const X_float first_dist = phi_inv * (x_max - x_min);
	std::array<X_float, 4> xs = {x_min, x_max - first_dist, x_min + first_dist, x_max};
	auto is_ordered = [&xs]() -> bool {
		for(int i = 0; i < 3; i++)
			if(xs[i] >= xs[i + 1]) return false;
		return true;
	};
	auto get = [&f, &x_max, &find_min](X_float x) -> Y { return find_min ? f(x) : -f(x); };
	Y y1 = get(xs[1]), y2 = get(xs[2]);
	for(; iteration_number > 0 && is_ordered(); iteration_number--) {
		if(y1 <= y2) {
			xs[3] = xs[2];
			xs[2] = xs[1];
			y2 = y1;
			xs[1] = xs[0] + (xs[2] - xs[0]) * phi_inv;
			y1 = get(xs[1]);
		} else {
			xs[0] = xs[1];
			xs[1] = xs[2];
			y1 = y2;
			xs[2] = xs[3] - (xs[3] - xs[1]) * phi_inv;
			y2 = get(xs[2]);
		}
	}
	Y x = xs[1] + (xs[2] - xs[1]) * X_float(0.5);
	return std::make_pair(x, f(x));
};

// calculate an approximation of iteration number for the golden section search
int approximate_iteration_number(long double start_len, long double eps) {
	constexpr long double inv_of_log_phi = 2.07808692123502753769L;	// phi = (sqrt(5) + 1) / 2, inv_of_log_phi = 1 / log(phi)
	return (start_len <= eps) ? 0 : int(ceill(logl(start_len / eps) * inv_of_log_phi));
}
#line 16 "SPJ-Library/graph/monge_graph_shortest_path.hpp"

// `calc_path_with_lambda(lbd)` is the shortest path from 0 to n-1 with cost c'(i, j) := c(i, j) + lbd
// returned value differs from the truth value by at most eps
template <class F, class float_type>  // `float_type` must be a float type (float, double, long double)
float_type monge_graph_shortest_path_with_d_edges(int d, const F& calc_path_with_lambda, float_type lambda_min, float_type lambda_max,
												  const float_type eps = 1e-6) {
	if(d == 0) return 0;
	assert(d > 0);
	auto L = [&d, &calc_path_with_lambda](float_type lbd) -> float_type { return calc_path_with_lambda(lbd) - lbd * d; };
	return golden_section_search_float<float_type, float_type, decltype(L)>(
			   L, lambda_min, lambda_max, approximate_iteration_number(lambda_max - lambda_min, eps / d) + 3, false)
		.second;
}

// `cost(from, to)` is the cost of edge `(from, to)`.
// time complexity: O(N^2 \log \max_{i, j} abs(c(i, j)))
template <class F, class float_type>  // `float_type` must be a float type (float, double, long double)
float_type monge_graph_shortest_path_with_d_edges_naive(int n, int d, const F& cost, const float_type eps = 1e-6) {
	assert(n > 0);
	if(n == 1) {
		assert(d == 0);
		return 0;
	}
	float_type cost_max = std::numeric_limits<float_type>::min();
	for(int i = 0; i < n; i++)
		for(int j = i + 1; j < n; j++) cost_max = std::max(cost_max, cost(i, j));
	const float_type lambda_max = 3 * (std::abs(cost_max) + 1);
	const float_type lambda_min = -lambda_max;
	auto calc_path_naive = [&](float_type lbd) -> float_type {
		std::vector<float_type> dist(n, std::numeric_limits<float_type>::max());
		dist[0] = 0;
		for(int i = 0; i < n; i++)
			for(int j = i + 1; j < n; j++) dist[j] = std::min(dist[j], dist[i] + cost(i, j) + lbd);
		return dist.back();
	};
	return monge_graph_shortest_path_with_d_edges(d, calc_path_naive, lambda_min, lambda_max, eps);
}
#line 7 "SPJ-Library/tests/monge_graph_shortest_path.test.cpp"

using namespace std;
using ll = long long;
using ld = long double;

ll solve() {
	int s, n, m;
	cin >> s >> n >> m;
	m = std::min(n, m);

	vector<ld> x(s);
	for(auto& y : x) cin >> y;
	vector<ld> arrive(n);
	for(int i = 0; i < n; i++) {
		ld tm;
		int idx;
		cin >> tm >> idx;
		idx--;
		arrive[i] = -(tm - x[idx]);
	}

	std::sort(begin(arrive), arrive.end());

	vector<ld> acc(n + 1);
	for(int i = 0; i < n; i++) acc[i + 1] = acc[i] + arrive[i];

	auto weight = [&](int from, int to) -> ld { return (acc[to] - acc[from]) - arrive[from] * (to - from); };

	constexpr ld eps = 1e-1;
	ld with_m_edges = monge_graph_shortest_path_with_d_edges_naive(n + 1, m, weight, eps);
	ll ret = ll(std::round(with_m_edges));
	assert(std::abs(ld(ret) - with_m_edges) <= eps);
	// cerr << std::abs(ld(ret) - with_m_edges) << '\n';
	// cerr << with_m_edges << '\n';
	return ret;
}

int main() { cout << solve() << '\n'; }
accuracy: 1
time_ms: 390
memory_kb: 3656
final_rank: 12

code_snippet: #line 1 "SPJ-Library/tests/monge_graph_shortest_path.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2603"
#include <cassert>
#include <iostream>
#include <vector>

#line 1 "SPJ-Library/graph/monge_graph_shortest_path.hpp"
// reference: https://noshi91.github.io/algorithm-encyclopedia/d-edge-shortest-path-monge
// calculate the minimum possible weight of a path from 0 to n-1 with exactly d edges on a complete DAG with Monge-ish weight edges
// problem settings:
// 	- given a graph satisfying the following conditions
//		- vertex set: {0, 1, ..., n-1}  (n >= 1)
// 		- edge set: {(i, j) | 0 <= i < j < n}  (directed)
// 		- Monge-ish weight of the edges: for all 0 <= i < j < k < l < n, c(i, k) + c(j, l) <= c(i, l) + c(j, k)
// 			- this resembles the definition of supermodular set functions
// 	- the task is to compute the shortest path with `d` edges (min{n - 1, 1} <= d < n) from 0 to n-1 on this graph
// time complexity:
// 	- in ordinary case, O(N^2 lg (max_{i, j} abs(c(i, j))))
// 	- when you can compute the shortest path without the constraint of the included edges in T(N) time, the whole complexity is
// 		O(T(N) lg (max_{i, j} abs(c(i, j))))

#line 1 "SPJ-Library/optimization/golden_section_search.hpp"
#include <algorithm>
#include <array>
#line 4 "SPJ-Library/optimization/golden_section_search.hpp"
#include <cmath>
#include <limits>
#include <tuple>

// find the min/aximum value of unimodal function `f` on [x_lb, x_ub), whose type is (F: X -> Y)
// constraints:
//	- X is an integer type (int, long long, __int128_t)
// 	- std::numeric_limits<X>::min() < x_lb < x_ub < std::numeric_limits<X>::max()
//	- (x_ub - x_lb) * 2 < std::numeric_limits<X>::max() - std::numeric_limits<X>::min()
// 	- f is unimodal
//		(i.e. if `find_min`, there exists two integers x_0, x_1 such that the following conditions hold:
// 		- x_lb <= x_0 <= x_1 < x_ub,
//		- for all x \in [x_lb, x_0), 		f(x) > f(x+1),
//		- for all x \in [x_0, x_1), 		f(x) == f(x+1),
//		- for all x \in [x_1, x_ub - 1), 	f(x) < f(x+1),
//		if not `find_min`, vice versa)
// usage:
// 		auto f = [](int x) -> ld { return sinl(ld(x) * pi / ld(180.)); };
// 		auto [x, y] = golden_section_search_int<int, ld, decltype(f)>(f, 57, 100, false); // (90, 1)
template <class X_int, class Y, class F>
std::pair<X_int, Y> golden_section_search_int(const F &f, X_int x_lb, X_int x_ub, bool find_min = true) {
	if(x_lb + 1 == x_ub) return std::make_pair(x_lb, f(x_lb));
	assert(x_lb < x_ub);
	std::array<X_int, 4> xs = {x_lb - 1, x_lb, x_lb + 1, x_lb + 2};
	while(xs.back() < x_ub) {
		xs[1] = xs[2];
		xs[2] = xs[3];
		xs[3] = xs[1] - xs[0] + xs[2];
	}
	auto get = [&f, &find_min](X_int x) -> Y { return find_min ? f(x) : -f(x); };
	Y y1 = get(xs[1]), y2 = get(xs[2]);
	auto right_is_smaller = [&x_ub, &xs, &y1, &y2]() -> bool { return xs[2] < x_ub && y1 > y2; };
	while(xs.back() - xs.front() > 3) {
		if(right_is_smaller()) {
			xs[0] = xs[1];
			xs[1] = xs[2];
			xs[2] = xs[3] - xs[1] + xs[0];
			y1 = y2;
			if(xs[2] < x_ub) y2 = get(xs[2]);
		} else {
			xs[3] = xs[2];
			xs[2] = xs[1];
			xs[1] = xs[3] - xs[2] + xs[0];
			y2 = y1;
			y1 = get(xs[1]);
		}
	}
	return right_is_smaller() ? std::make_pair(xs[2], find_min ? y2 : -y2) : std::make_pair(xs[1], find_min ? y1 : -y1);
};

// find the min/aximum value of unimodal function `f` on [x_min, x_max], whose type is (F: X -> Y)
// returns f(x), where x is in [x* - eps, x* + eps] and x* is the optimal solution
// constraints:
//	- X (= X_float) is a floating point number type (float, double, long double)
// 	- std::numeric_limits<X>::min() < x_min <= x_max
//	- (x_max - x_min) * 2 < std::numeric_limits<X>::max() - std::numeric_limits<X>::min()
// 	- f is unimodal
//		(i.e. if `find_min`, there exists two integers x_0, x_1 such that the following conditions hold:
// 		- x_min <= x_0 <= x_1 <= x_max,
//		- for all x \in (x_min, x_0), 	f'(x) < 0,
//		- for all x \in (x_0, x_1), 	f'(x) == 0,
//		- for all x \in (x_1, x_max), 	f'(x) > 0,
//		if not `find_min`, vice versa)
// usage:
// 		auto f = [](ld x) -> ld { return sinl(x * pi / ld(180.)); };
// 		auto [x, y] = golden_section_search_float<ld, ld, decltype(f)>(f, 57, 100, false); // (90, 1)
template <class X_float, class Y, class F>
std::pair<X_float, Y> golden_section_search_float(const F &f, X_float x_min, X_float x_max, int iteration_number, bool find_min = true) {
	assert(x_min <= x_max);
	constexpr long double phi_inv = 0.6180339887498949L;  // (sqrt(5) - 1) / 2
	const X_float first_dist = phi_inv * (x_max - x_min);
	std::array<X_float, 4> xs = {x_min, x_max - first_dist, x_min + first_dist, x_max};
	auto is_ordered = [&xs]() -> bool {
		for(int i = 0; i < 3; i++)
			if(xs[i] >= xs[i + 1]) return false;
		return true;
	};
	auto get = [&f, &x_max, &find_min](X_float x) -> Y { return find_min ? f(x) : -f(x); };
	Y y1 = get(xs[1]), y2 = get(xs[2]);
	for(; iteration_number > 0 && is_ordered(); iteration_number--) {
		if(y1 <= y2) {
			xs[3] = xs[2];
			xs[2] = xs[1];
			y2 = y1;
			xs[1] = xs[0] + (xs[2] - xs[0]) * phi_inv;
			y1 = get(xs[1]);
		} else {
			xs[0] = xs[1];
			xs[1] = xs[2];
			y1 = y2;
			xs[2] = xs[3] - (xs[3] - xs[1]) * phi_inv;
			y2 = get(xs[2]);
		}
	}
	Y x = xs[1] + (xs[2] - xs[1]) * X_float(0.5);
	return std::make_pair(x, f(x));
};

// calculate an approximation of iteration number for the golden section search
int approximate_iteration_number(long double start_len, long double eps) {
	constexpr long double inv_of_log_phi = 2.07808692123502753769L;	// phi = (sqrt(5) + 1) / 2, inv_of_log_phi = 1 / log(phi)
	return (start_len <= eps) ? 0 : int(ceill(logl(start_len / eps) * inv_of_log_phi));
}
#line 16 "SPJ-Library/graph/monge_graph_shortest_path.hpp"

// `calc_path_with_lambda(lbd)` is the shortest path from 0 to n-1 with cost c'(i, j) := c(i, j) + lbd
// returned value differs from the truth value by at most eps
template <class F, class float_type> // `float_type` must be a float type (float, double, long double)
float_type monge_graph_shortest_path_with_d_edges(int d, const F& calc_path_with_lambda, float_type lambda_min, float_type lambda_max, const float_type eps = 1e-6) {
	if(d == 0) return 0;
	assert(d > 0);
	auto L = [&d, &calc_path_with_lambda](float_type lbd) -> float_type { return calc_path_with_lambda(lbd) - lbd * d; };
	return golden_section_search_float<float_type, float_type, decltype(L)>(L, lambda_min, lambda_max,
															approximate_iteration_number(lambda_max - lambda_min, eps / d) + 3, false)
		.second;
}

// `cost(from, to)` is the cost of edge `(from, to)`.
// time complexity: O(N^2 \log \max_{i, j} abs(c(i, j)))
template <class F, class float_type>
float_type monge_graph_shortest_path_with_d_edges_naive(int n, int d, const F& cost, const float_type eps = 1e-6) {
	assert(n > 0);
	if(n == 1) {
		assert(d == 0);
		return 0;
	}
	float_type cost_max = std::numeric_limits<float_type>::min();
	for(int i = 0; i < n; i++)
		for(int j = i + 1; j < n; j++) cost_max = std::max(cost_max, cost(i, j));
	const float_type lambda_max = 3 * (std::abs(cost_max) + 1);
	const float_type lambda_min = -lambda_max;
	auto calc_path_naive = [&](float_type lbd) -> float_type {
		std::vector<float_type> dist(n, std::numeric_limits<float_type>::max());
		dist[0] = 0;
		for(int i = 0; i < n; i++)
			for(int j = i + 1; j < n; j++) dist[j] = std::min(dist[j], dist[i] + cost(i, j) + lbd);
		return dist.back();
	};
	return monge_graph_shortest_path_with_d_edges(d, calc_path_naive, lambda_min, lambda_max, eps);
}
#line 7 "SPJ-Library/tests/monge_graph_shortest_path.test.cpp"

using namespace std;
using ll = long long;
using ld = long double;

ll solve() {
	int s, n, m;
	cin >> s >> n >> m;
	m = std::min(n, m);

	vector<ld> x(s);
	for(auto& y : x) cin >> y;
	vector<ld> arrive(n);
	for(int i = 0; i < n; i++) {
		ld tm;
		int idx;
		cin >> tm >> idx;
		idx--;
		arrive[i] = -(tm - x[idx]);
	}

	std::sort(begin(arrive), arrive.end());

	vector<ld> acc(n + 1);
	for(int i = 0; i < n; i++) acc[i + 1] = acc[i] + arrive[i];

	auto weight = [&](int from, int to) -> ld { return (acc[to] - acc[from]) - arrive[from] * (to - from); };

	constexpr ld eps = 1e-6;
	ld with_m_edges = monge_graph_shortest_path_with_d_edges_naive(n + 1, m, weight, eps);
	ll ret = ll(std::round(with_m_edges));
	assert(std::abs(ld(ret) - with_m_edges) <= eps);
	return ret;
}

int main() { cout << solve() << '\n'; }
accuracy: 1
time_ms: 530
memory_kb: 3668
final_rank: 13

code_snippet: #line 1 "d.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2603"
#include <iostream>
#include <vector>

#line 1 "SPJ-Library/optimization/golden_section_search.hpp"
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <limits>
#include <tuple>

// find the min/aximum value of unimodal function `f` on [x_lb, x_ub), whose type is (F: X -> Y)
// constraints:
//	- X is an integer type (int, long long, __int128_t)
// 	- std::numeric_limits<X>::min() < x_lb < x_ub
//	- (x_ub - x_lb) * 2 < std::numeric_limits<X>::max() - std::numeric_limits<X>::min()
//	- max_{x \in [x_lb, x_ub)} abs(f(x)) < INF
// 	- f is unimodal
//		(i.e. if `find_min`, there exists two integers x_0, x_1 such that the following conditions hold:
// 		- x_lb <= x_0 <= x_1 < x_ub,
//		- for all x \in [x_lb, x_0), 		f(x) > f(x+1),
//		- for all x \in [x_0, x_1), 		f(x) == f(x+1),
//		- for all x \in [x_1, x_ub - 1), 	f(x) < f(x+1),
//		if not `find_min`, vice versa)
// usage:
// 		auto f = [](int x) -> ld { return sinl(ld(x) * pi / ld(180.)); };
// 		auto [x, y] = golden_section_search_int<int, ld, decltype(f)>(f, 57, 100, false); // (90, 1)
template <class X_int, class Y, class F>
std::pair<X_int, Y> golden_section_search_int(const F &f, X_int x_lb, X_int x_ub, bool find_min = true,
											  Y INF = std::numeric_limits<Y>::max()) {
	assert(x_lb < x_ub);
	std::array<X_int, 4> xs = {x_lb - 1, x_lb, x_lb + 1, x_lb + 2};
	while(xs.back() < x_ub) {
		xs[1] = xs[2];
		xs[2] = xs[3];
		xs[3] = xs[1] - xs[0] + xs[2];
	}
	auto get = [&f, &x_ub, &find_min, &INF](X_int x) -> Y {
		if(x_ub <= x) return INF;
		return find_min ? f(x) : -f(x);
	};
	Y y1 = get(xs[1]), y2 = get(xs[2]);
	while(xs.back() - xs.front() > 3) {
		if(y1 <= y2) {
			xs[3] = xs[2];
			xs[2] = xs[1];
			xs[1] = xs[3] - xs[2] + xs[0];
			y2 = y1;
			y1 = get(xs[1]);
		} else {
			xs[0] = xs[1];
			xs[1] = xs[2];
			xs[2] = xs[3] - xs[1] + xs[0];
			y1 = y2;
			y2 = get(xs[2]);
		}
	}
	Y y = std::min(y1, y2);
	return std::make_pair((y1 < y2 ? xs[1] : xs[2]), find_min ? y : -y);
};

// find the min/aximum value of unimodal function `f` on [x_min, x_max], whose type is (F: X -> Y)
// returns f(x), where x is in [x* - eps, x* + eps] and x* is the optimal solution
// constraints:
//	- X (= X_float) is a floating point number type (float, double, long double)
// 	- std::numeric_limits<X>::min() < x_min <= x_max
//	- (x_max - x_min) * 2 < std::numeric_limits<X>::max() - std::numeric_limits<X>::min()
//	- max_{x \in [x_min, x_max]} abs(f(x)) < INF
// 	- f is unimodal
//		(i.e. if `find_min`, there exists two integers x_0, x_1 such that the following conditions hold:
// 		- x_min <= x_0 <= x_1 <= x_max,
//		- for all x \in (x_min, x_0), 	f'(x) < 0,
//		- for all x \in (x_0, x_1), 	f'(x) == 0,
//		- for all x \in (x_1, x_max), 	f'(x) > 0,
//		if not `find_min`, vice versa)
// usage:
// 		auto f = [](ld x) -> ld { return sinl(x * pi / ld(180.)); };
// 		auto [x, y] = golden_section_search_float<ld, ld, decltype(f)>(f, 57, 100, false); // (90, 1)
template <class X_float, class Y, class F>
std::pair<X_float, Y> golden_section_search_float(const F &f, X_float x_min, X_float x_max, int repeat_number, bool find_min = true,
												  Y INF = std::numeric_limits<Y>::max()) {
	assert(x_min <= x_max);
	constexpr long double phi_inv = (sqrtl(5) - 1.0L) * 0.5L;
	const X_float first_dist = phi_inv * (x_max - x_min);
	std::array<X_float, 4> xs = {x_min, x_max - first_dist, x_min + first_dist, x_max};
	auto is_ordered = [&xs]() -> bool {
		for(int i = 0; i < 3; i++)
			if(xs[i] >= xs[i + 1]) return false;
		return true;
	};
	auto get = [&f, &x_max, &find_min, &INF](X_float x) -> Y {
		if(x_max < x) return INF;
		return find_min ? f(x) : -f(x);
	};
	Y y1 = get(xs[1]), y2 = get(xs[2]);
	for(; repeat_number > 0 && is_ordered(); repeat_number--) {
		if(y1 <= y2) {
			xs[3] = xs[2];
			xs[2] = xs[1];
			y2 = y1;
			xs[1] = xs[0] + (xs[2] - xs[0]) * phi_inv;
			y1 = get(xs[1]);
		} else {
			xs[0] = xs[1];
			xs[1] = xs[2];
			y1 = y2;
			xs[2] = xs[3] - (xs[3] - xs[1]) * phi_inv;
			y2 = get(xs[2]);
		}
	}
	Y x = xs[1] + (xs[2] - xs[1]) * X_float(0.5);
	return std::make_pair(x, f(x));
};
#line 6 "d.cpp"

using namespace std;
using ll = long long;
using ld = long double;

ll solve() {
	int s, n, m;
	cin >> s >> n >> m;
	m = std::min(n, m);

	vector<ld> x(s);
	for(auto& y : x) cin >> y;
	vector<ld> arrive(n);
	for(int i = 0; i < n; i++) {
		ld tm;
		int idx;
		cin >> tm >> idx;
		idx--;
		arrive[i] = -(tm - x[idx]);
	}

	std::sort(begin(arrive), arrive.end());

	vector<ld> acc(n + 1);
	for(int i = 0; i < n; i++) acc[i + 1] = acc[i] + arrive[i];

	auto weight = [&](int from, int to) -> ld { return (acc[to] - acc[from]) - arrive[from] * (to - from); };

	const ld cost_max = weight(0, n);
	const ld lambda_max = (cost_max + 5) * 5;
	const ld INF = lambda_max * n + cost_max * n + 10;

	auto calc_path = [&](ld lbd) -> ld {
		vector<ld> res(n + 1, INF);
		res[0] = 0;
		for(int from = 0; from < n; from++) {
			for(int to = from + 1; to <= n; to++) { res[to] = std::min(res[to], res[from] + weight(from, to) + lbd); }
		}
		return res.back();
	};

	auto L = [&m, &calc_path](ld lbd) -> ld { return calc_path(lbd) - lbd * m; };

	ld with_m_edges = golden_section_search_float<ld, ld, decltype(L)>(L, -lambda_max, lambda_max, 50, false, INF).second;
	if(with_m_edges <= 0) return 0;
	ll ret = ll(with_m_edges);
	if(with_m_edges - ld(ret) > 0.5) ret++;
	return ret;
}

int main() { cout << solve() << '\n'; }
accuracy: 1
time_ms: 320
memory_kb: 3624
final_rank: 11

code_snippet: // time complexity: O(N^1.5 * M^0.5 * (maxX+maxT)^0.5)

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

int solve(int N, int M, const vector<int>& V) {
	if (M >= N) {
		return 0;
	}
	int lim = (V[N - 1] + 1) / M * N;
	int stride = 0;
	while (stride * (stride + 1) / 2 <= lim) {
		stride += 1;
	}
	const int INF = 1012345678;
	vector<int> comp = V;
	comp.erase(unique(comp.begin(), comp.end()), comp.end());
	int K = comp.size();
	vector<int> cnt(K);
	int pos = 0;
	for (int i = 0; i < N; i++) {
		while (comp[pos] != V[i]) {
			pos += 1;
		}
		cnt[pos] += 1;
	}
	vector<vector<int> > dp(K + 1, vector<int>(M + 1, INF));
	dp[0][0] = 0;
	for (int i = 1; i <= K; i++) {
		for (int j = 1; j <= M; j++) {
			int cost = 0;
			for (int k = i - 1; k >= 0 && k >= i - stride; k--) {
				cost += cnt[k] * (comp[i - 1] - comp[k]);
				if (dp[k][j - 1] != INF) {
					dp[i][j] = min(dp[i][j], dp[k][j - 1] + cost);
				}
			}
		}
	}
	return dp[K][M];
}

int main() {
	int S, N, M;
	cin >> S >> N >> M;
	vector<int> X(S);
	for (int i = 0; i < S; i++) {
		cin >> X[i];
	}
	vector<int> T(N), P(N);
	for (int i = 0; i < N; i++) {
		cin >> T[i] >> P[i];
	}
	vector<int> V(N);
	for (int i = 0; i < N; i++) {
		V[i] = T[i] - X[P[i] - 1];
	}
	sort(V.begin(), V.end());
	int offset = V[0];
	for (int i = 0; i < N; i++) {
		V[i] -= offset;
	}
	int ans = solve(N, M, V);
	cout << ans << endl;
	return 0;
}
accuracy: 1
time_ms: 610
memory_kb: 10052
final_rank: 15

code_snippet: // time complexity: O(N^1.5 * M^0.5 * (maxX+maxT)^0.5)

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

int solve(int N, int M, const vector<int>& V) {
	int lim = (V[N - 1] + 1) / M * N;
	int stride = 0;
	while (stride * (stride + 1) / 2 <= lim) {
		stride += 1;
	}
	const int INF = 1012345678;
	vector<int> comp = V;
	comp.erase(unique(comp.begin(), comp.end()), comp.end());
	int K = comp.size();
	vector<int> cnt(K);
	int pos = 0;
	for (int i = 0; i < N; i++) {
		while (comp[pos] != V[i]) {
			pos += 1;
		}
		cnt[pos] += 1;
	}
	vector<vector<int> > dp(K + 1, vector<int>(M + 1, INF));
	dp[0][0] = 0;
	for (int i = 1; i <= K; i++) {
		for (int j = 1; j <= M; j++) {
			int cost = 0;
			for (int k = i - 1; k >= 0 && k >= i - stride; k--) {
				cost += cnt[k] * (comp[i - 1] - comp[k]);
				dp[i][j] = min(dp[i][j], dp[k][j - 1] + cost);
			}
		}
	}
	return dp[K][M];
}

int main() {
	int S, N, M;
	cin >> S >> N >> M;
	vector<int> X(S);
	for (int i = 0; i < S; i++) {
		cin >> X[i];
	}
	vector<int> T(N), P(N);
	for (int i = 0; i < N; i++) {
		cin >> T[i] >> P[i];
	}
	vector<int> V(N);
	for (int i = 0; i < N; i++) {
		V[i] = T[i] - X[P[i] - 1];
	}
	sort(V.begin(), V.end());
	int offset = V[0];
	for (int i = 0; i < N; i++) {
		V[i] -= offset;
	}
	int ans = solve(N, M, V);
	cout << ans << endl;
	return 0;
}
accuracy: 0.07407407407407407
time_ms: 40
memory_kb: 4188
final_rank: 17

code_snippet: // time complexity: O(N^1.5 * M^0.5 * (maxX+maxT)^0.5)

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

int solve(int N, int M, const vector<int>& V) {
	int lim = (V[N - 1] + 1) / M * N;
	int stride = 0;
	while (stride * (stride + 1) / 2 <= lim) {
		stride += 1;
	}
	const int INF = 1012345678;
	vector<int> comp = V;
	comp.erase(unique(comp.begin(), comp.end()), comp.end());
	int K = comp.size();
	vector<int> cnt(K);
	int pos = 0;
	for (int i = 0; i < N; i++) {
		while (comp[pos] != V[i]) {
			pos += 1;
		}
		cnt[pos] += 1;
	}
	vector<vector<int> > dp(K + 1, vector<int>(M + 1, INF));
	dp[0][0] = 0;
	for (int i = 1; i <= K; i++) {
		for (int j = 1; j <= M; j++) {
			int cost = 0;
			for (int k = i - 1; k >= 0/* && k >= j - stride*/; k--) {
				cost += cnt[k] * (comp[i - 1] - comp[k]);
				dp[i][j] = min(dp[i][j], dp[k][j - 1] + cost);
			}
		}
	}
	return dp[K][M];
}

int main() {
	int S, N, M;
	cin >> S >> N >> M;
	vector<int> X(S);
	for (int i = 0; i < S; i++) {
		cin >> X[i];
	}
	vector<int> T(N), P(N);
	for (int i = 0; i < N; i++) {
		cin >> T[i] >> P[i];
	}
	vector<int> V(N);
	for (int i = 0; i < N; i++) {
		V[i] = T[i] - X[P[i] - 1];
	}
	sort(V.begin(), V.end());
	int offset = V[0];
	for (int i = 0; i < N; i++) {
		V[i] -= offset;
	}
	int ans = solve(N, M, V);
	cout << ans << endl;
	return 0;
}
accuracy: 0.07407407407407407
time_ms: 80
memory_kb: 4412
final_rank: 20

code_snippet: // time complexity: O(N^1.5 * M^0.5 * (maxX+maxT)^0.5)

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

int solve(int N, int M, const vector<int>& V) {
	int lim = (V[N - 1] + 1) / M * N;
	int stride = 0;
	while (stride * (stride + 1) / 2 <= lim) {
		stride += 1;
	}
	const int INF = 1012345678;
	vector<int> comp = V;
	comp.erase(unique(comp.begin(), comp.end()), comp.end());
	int K = comp.size();
	vector<int> cnt(K);
	int pos = 0;
	for (int i = 0; i < N; i++) {
		while (comp[pos] != V[i]) {
			pos += 1;
		}
		cnt[pos] += 1;
	}
	vector<vector<int> > dp(K + 1, vector<int>(M + 1, INF));
	dp[0][0] = 0;
	for (int i = 1; i <= K; i++) {
		for (int j = 1; j <= M; j++) {
			int cost = 0;
			for (int k = i - 1; k >= 0 && k >= j - stride; k--) {
				cost += cnt[k] * (comp[i - 1] - comp[k]);
				dp[i][j] = min(dp[i][j], dp[k][j - 1] + cost);
			}
		}
	}
	return dp[K][M];
}

int main() {
	int S, N, M;
	cin >> S >> N >> M;
	vector<int> X(S);
	for (int i = 0; i < S; i++) {
		cin >> X[i];
	}
	vector<int> T(N), P(N);
	for (int i = 0; i < N; i++) {
		cin >> T[i] >> P[i];
	}
	vector<int> V(N);
	for (int i = 0; i < N; i++) {
		V[i] = T[i] - X[P[i] - 1];
	}
	sort(V.begin(), V.end());
	int offset = V[0];
	for (int i = 0; i < N; i++) {
		V[i] -= offset;
	}
	int ans = solve(N, M, V);
	cout << ans << endl;
	return 0;
}
accuracy: 0.07407407407407407
time_ms: 40
memory_kb: 4344
final_rank: 18

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

long long S, X[2009];
long long N, T[2009], P[2009];
long long M;
long long dp[2009][2009];

int main() {
	// Step 1. Input
	cin >> S >> N >> M;
	for (int i = 1; i <= S; i++) cin >> X[i];
	for (int i = 1; i <= N; i++) cin >> T[i] >> P[i];

	// Step 2. DP Init
	for (int i = 1; i <= M; i++) {
		for (int j = 0; j < N; j++) dp[i][j] = (1LL << 60);
	}

	// Step 3. Initialize
	vector<long long> A;
	for (int i = 1; i <= N; i++) A.push_back(T[i] - X[P[i]]);
	sort(A.begin(), A.end());
	for (int i = 0; i < N; i++) dp[1][i] = A[i] * (i + 1);

	// Step 4. Dynamic Programming
	for (int i = 2; i <= M; i++) {
		vector<tuple<long long, long long, long long>> tup;
		for (int j = 0; j < N; j++) {
			long long px = j;
			long long py = dp[i - 1][j];

			// Pop Phase
			while (tup.size() >= 2) {
				long long diff1_x = get<1>(tup[tup.size() - 1]) - get<1>(tup[tup.size() - 2]);
				long long diff1_y = get<2>(tup[tup.size() - 1]) - get<2>(tup[tup.size() - 2]);
				long long diff2_x = px - get<1>(tup[tup.size() - 1]);
				long long diff2_y = py - get<2>(tup[tup.size() - 1]);
				if (diff1_x * diff2_y > diff1_y * diff2_x) break;
				tup.pop_back();
			}
			long long katamuki = 0;
			if (tup.size() >= 1) katamuki = (py - get<2>(tup[tup.size() - 1])) / (px - get<1>(tup[tup.size() - 1]));
			tup.push_back(make_tuple(katamuki, px, py));

			// Binary Search Phase
			int pos1 = lower_bound(tup.begin(), tup.end(), make_tuple(A[j], -1LL, -1LL)) - tup.begin();
			vector<int> cand;
			if (pos1 < tup.size()) cand.push_back(get<1>(tup[pos1]));
			if (pos1 >= 1) cand.push_back(get<1>(tup[pos1 - 1]));

			// Transition Phase
			for (int k : cand) {
				dp[i][j] = min(dp[i][j], dp[i - 1][k] + A[j] * (j - k));
			}
		}
	}

	// Step 5. Output
	long long Sum = 0;
	for (int i = 0; i < N; i++) Sum += A[i];
	cout << dp[M][N - 1] - Sum << endl;
	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 32804
final_rank: 10

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

long long S, X[2009];
long long N, T[2009], P[2009];
long long M;
long long dp[2009][2009];

int main() {
	// Step 1. Input
	cin >> S >> N >> M;
	for (int i = 1; i <= S; i++) cin >> X[i];
	for (int i = 1; i <= N; i++) cin >> T[i] >> P[i];

	// Step 2. DP Init
	for (int i = 1; i <= M; i++) {
		for (int j = 0; j < N; j++) dp[i][j] = (1LL << 60);
	}

	// Step 3. Initialize
	vector<long long> A;
	for (int i = 1; i <= N; i++) A.push_back(T[i] - X[P[i]]);
	sort(A.begin(), A.end());
	for (int i = 0; i < N; i++) dp[1][i] = A[i] * (i + 1);

	// Step 4. Dynamic Programming
	for (int i = 2; i <= M; i++) {
		vector<tuple<long long, long long, long long>> tup;
		for (int j = 0; j < N; j++) {
			long long px = j;
			long long py = dp[i - 1][j];

			// Pop Phase
			while (tup.size() >= 2) {
				long long diff1_x = get<1>(tup[tup.size() - 1]) - get<1>(tup[tup.size() - 1]);
				long long diff1_y = get<2>(tup[tup.size() - 1]) - get<2>(tup[tup.size() - 1]);
				long long diff2_x = px - get<1>(tup[tup.size() - 1]);
				long long diff2_y = py - get<1>(tup[tup.size() - 1]);
				if (diff1_x * diff2_y > diff1_y * diff2_x) break;
				tup.pop_back();
			}
			long long katamuki = 0;
			if (tup.size() >= 1) katamuki = (py - get<2>(tup[tup.size() - 1])) / (px - get<1>(tup[tup.size() - 1]));
			tup.push_back(make_tuple(katamuki, px, py));

			// Binary Search Phase
			int pos1 = lower_bound(tup.begin(), tup.end(), make_tuple(A[j], -1LL, -1LL)) - tup.begin();
			vector<int> cand;
			if (pos1 < tup.size()) cand.push_back(get<1>(tup[pos1]));
			if (pos1 >= 1) cand.push_back(get<1>(tup[pos1 - 1]));

			// Transition Phase
			for (int k : cand) {
				dp[i][j] = min(dp[i][j], dp[i - 1][k] + A[j] * (j - k));
			}
		}
	}

	// Step 5. Output
	long long Sum = 0;
	for (int i = 0; i < N; i++) Sum += A[i];
	cout << dp[M][N - 1] - Sum << endl;
	return 0;
}
accuracy: 0.07407407407407407
time_ms: 10
memory_kb: 14672
final_rank: 19

code_snippet: #line 1 "a.cpp"
// cSpell:disable
/*	author:  Kite_kuma
	created: 2023.04.03 12:32:09 */

// #ifdef LOCAL
// #define _GLIBCXX_DEBUG
// #endif
#line 2 "SPJ-Library/template/kuma.hpp"

#line 2 "SPJ-Library/template/basic_func.hpp"

#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>

template <class T0, class T1, class T2>
inline bool in_range(T0 x, T1 lef, T2 rig) {
	return ((lef <= x) && (x < rig));
}

template <class T>
inline bool chmin(T &a, T b) {
	if(a > b) {
		a = b;
		return true;
	}
	return false;
}
template <class T>
inline bool chmax(T &a, T b) {
	if(a < b) {
		a = b;
		return true;
	}
	return false;
}

void Yes(bool flag = true) { std::cout << (flag ? "Yes" : "No") << '\n'; }
void YES(bool flag = true) { std::cout << (flag ? "YES" : "NO") << '\n'; }

template <class T>
void drop(T answer) {
	std::cout << answer << '\n';
	exit(0);
}

template <class T>
void vout(std::vector<T> const &v, bool vertically = 0) {
	if(vertically) {
		for(auto const &a : v) {
			std::cout << a << '\n';
		}
		return;
	}
	for(auto it = v.begin(); it != v.end(); it++) {
		std::cout << (*it);
		if(it != v.end() - 1) {
			std::cout << ' ';
		}
	}
	std::cout << '\n';
	return;
}

inline void print() { std::cout << '\n'; }
template <class T>
inline void print(const T &x) {
	std::cout << x << '\n';
	return;
}
template <typename Head, typename... Tail>
void print(const Head &H, const Tail &... T) {
	std::cout << H << " ";
	print(T...);
}

template <class T>
void add(std::vector<T> &v, T value) {
	for(auto &a : v) a += value;
	return;
}

template <class T>
T greatest_lower_multiple(T x, T d) {
	if(d == 0) return 0;
	if(d < 0) d *= -1;
	T y = x % d;
	if(y < 0) y += d;
	return x - y;
}

template <class T>
T least_upper_multiple(T x, T d) {
	return -greatest_lower_multiple(-x, d);
}

// ceil(a / b);
template <class T>
T dup(T a, T b) {
	assert(b);
	if(b < 0) {
		a *= -1;
		b *= -1;
	}
	return least_upper_multiple(a, b) / b;
}

long long pow_ll(long long a, long long n) {
	assert(n >= 0LL);
	if(n == 0) return 1LL;
	if(a == 0) return 0LL;
	if(a == 1) return 1LL;
	if(a == -1) return (n & 1LL) ? -1LL : 1LL;
	long long res = 1;
	while(n > 1LL) {
		if(n & 1LL) res *= a;
		a *= a;
		n >>= 1;
	}
	return res * a;
}

// @return: x  s.t. x == a^n, 0 <= x < abs(mod)
// @require: mod != 0, abs(mod) < 2e9
long long modpow(long long a, long long n, long long mod) {
	assert(n >= 0 && mod);
	mod = mod > 0 ? mod : -mod;
	if(mod == 1) return 0LL;
	long long res = 1;
	a %= mod;
	while(n) {
		if(n & 1) (res *= a) %= mod;
		(a *= a) %= mod;
		n >>= 1;
	}
	return res < 0 ? res + mod : res;
}

// @return: x  s.t. a * x % mod == gcd(a, mod), 0 <= x < mod
// @require: a % mod != 0
long long modinv(long long a, long long mod) {
	assert(mod && a % mod);
	mod = mod > 0 ? mod : -mod;
	long long b = mod, u = 1, v = 0;
	while(b) {
		long long t = a / b;
		a -= t * b;
		std::swap(a, b);
		u -= t * v;
		std::swap(u, v);
	}
	u %= mod;
	return u < 0 ? u + mod : u;
}

template <class T>
int lb(const std::vector<T> &a, const T &x) {
	return (int)std::distance(a.begin(), std::lower_bound(a.begin(), a.end(), x));
}
template <class T>
int ub(const std::vector<T> &a, const T &x) {
	return (int)std::distance(a.begin(), std::upper_bound(a.begin(), a.end(), x));
}
template <class T>
void unq_sort(std::vector<T> &a) {
	std::sort(a.begin(), a.end());
	a.erase(std::unique(a.begin(), a.end()), a.end());
}
template <class T>
std::vector<int> press(const std::vector<T> &a) {
	std::vector<T> vec = a;
	unq_sort(vec);
	std::vector<int> ret;
	for(const auto &v : a) ret.push_back(lb(vec, v));
	return ret;
}
#line 1 "SPJ-Library/template/header.hpp"
#include <bits/stdc++.h>
#line 2 "SPJ-Library/template/io.hpp"

#line 4 "SPJ-Library/template/io.hpp"

#line 8 "SPJ-Library/template/debug.hpp"

#line 3 "SPJ-Library/template/constants.hpp"

constexpr int inf = 1000'000'000;
constexpr long long INF = 1'000'000'000'000'000'000LL;
constexpr int mod_1000000007 = 1000000007;
constexpr int mod_998244353 = 998244353;
const long double pi = acosl(-1.);
constexpr int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
constexpr int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
#line 10 "SPJ-Library/template/debug.hpp"

namespace viewer {

template <typename T, typename U>
void view(const std::pair<T, U> &p);

template <class T0, class T1, class T2>
void view(const std::tuple<T0, T1, T2> &p);

template <class T0, class T1, class T2, class T3>
void view(const std::tuple<T0, T1, T2, T3> &p);

void view(const long long &e);

void view(const int &e);

template <typename T>
void view(const T &e);

template <typename T>
void view(const std::set<T> &s);

template <typename T>
void view(const std::unordered_set<T> &s);

template <typename T>
void view(const std::multiset<T> &s);

template <typename T>
void view(const std::unordered_multiset<T> &s);

template <typename T>
void view(const std::vector<T> &v);

template <typename T, std::size_t ary_size>
void view(const std::array<T, ary_size> &v);

template <typename T>
void view(const std::vector<std::vector<T>> &vv);

template <typename T, typename U>
void view(const std::vector<std::pair<T, U>> &v);

template <class T0, class T1, class T2>
void view(const std::vector<std::tuple<T0, T1, T2>> &v);

template <class T0, class T1, class T2, class T3>
void view(const std::vector<std::tuple<T0, T1, T2, T3>> &v);

template <typename map_type>
void view_map_container(const map_type &m);

template <typename T, typename U>
void view(const std::map<T, U> &m);

template <typename T, typename U>
void view(const std::unordered_map<T, U> &m);

template <typename container_type>
void view_container(const container_type &c, bool vertically = false) {
	typename container_type::const_iterator begin = c.begin();
	const typename container_type::const_iterator end = c.end();
	if(vertically) {
		std::cerr << "{\n";
		while(begin != end) {
			std::cerr << '\t';
			view(*(begin++));
			if(begin != end) std::cerr << ',';
			std::cerr << '\n';
		}
		std::cerr << '}';
		return;
	}
	std::cerr << "{ ";
	while(begin != end) {
		view(*(begin++));
		if(begin != end) std::cerr << ',';
		std::cerr << ' ';
	}
	std::cerr << '}';
}

template <typename T, typename U>
void view(const std::pair<T, U> &p) {
	std::cerr << '(';
	view(p.first);
	std::cerr << ", ";
	view(p.second);
	std::cerr << ')';
}

template <class T0, class T1, class T2>
void view(const std::tuple<T0, T1, T2> &p) {
	std::cerr << '(';
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ')';
}

template <class T0, class T1, class T2, class T3>
void view(const std::tuple<T0, T1, T2, T3> &p) {
	std::cerr << '(';
	view(std::get<0>(p));
	std::cerr << ", ";
	view(std::get<1>(p));
	std::cerr << ", ";
	view(std::get<2>(p));
	std::cerr << ", ";
	view(std::get<3>(p));
	std::cerr << ')';
}

void view(const long long &e) {
	if(e == INF)
		std::cerr << "INF";
	else if(e == -INF)
		std::cerr << "-INF";
	else
		std::cerr << e;
}

void view(const int &e) {
	if(e == inf)
		std::cerr << "inf";
	else if(e == -inf)
		std::cerr << "-inf";
	else
		std::cerr << e;
}

template <typename T>
void view(const T &e) {
	std::cerr << e;
}

template <typename T>
void view(const std::set<T> &s) {
	view_container(s);
}

template <typename T>
void view(const std::unordered_set<T> &s) {
	view_container(s);
}

template <typename T>
void view(const std::multiset<T> &s) {
	view_container(s);
}

template <typename T>
void view(const std::unordered_multiset<T> &s) {
	view_container(s);
}

template <typename T>
void view(const std::vector<T> &v) {
	view_container(v);
}

template <typename T, std::size_t ary_size>
void view(const std::array<T, ary_size> &v) {
	view_container(v);
}

template <typename T>
void view(const std::vector<std::vector<T>> &vv) {
	view_container(vv, true);
}

template <typename T, typename U>
void view(const std::vector<std::pair<T, U>> &v) {
	view_container(v, true);
}

template <class T0, class T1, class T2>
void view(const std::vector<std::tuple<T0, T1, T2>> &v) {
	view_container(v, true);
}

template <class T0, class T1, class T2, class T3>
void view(const std::vector<std::tuple<T0, T1, T2, T3>> &v) {
	view_container(v, true);
}

template <typename map_type>
void view_map_container(const map_type &m) {
	std::cerr << "{\n";
	for(typename map_type::const_iterator it = m.begin(); it != m.end(); it++) {
		std::cerr << "\t[";
		view(it->first);
		std::cerr << "] : ";
		view(it->second);
		std::cerr << '\n';
	}
	std::cerr << "}";
}

template <typename T, typename U>
void view(const std::map<T, U> &m) {
	view_map_container(m);
}

template <typename T, typename U>
void view(const std::unordered_map<T, U> &m) {
	view_map_container(m);
}

}  // namespace viewer

// when compiling : g++ foo.cpp -DLOCAL
#ifdef LOCAL
void debug_out() {}
template <typename T>
void debug_out(const T &x) {
	viewer::view(x);
}
template <typename Head, typename... Tail>
void debug_out(const Head &H, const Tail &... T) {
	viewer::view(H);
	std::cerr << ", ";
	debug_out(T...);
}
#define debug(...)                                                \
	do {                                                          \
		std::cerr << __LINE__ << " [" << #__VA_ARGS__ << "] : ["; \
		debug_out(__VA_ARGS__);                                   \
		std::cerr << "]\n";                                       \
	} while(0)
#else
#define debug(...) (void(0))
#endif
#line 2 "SPJ-Library/template/scanner.hpp"

#line 6 "SPJ-Library/template/scanner.hpp"

namespace scanner {
template <class T>
void scan(T &a) {
	std::cin >> a;
}

template <class T, class L>
void scan(std::pair<T, L> &p) {
	scan(p.first);
	scan(p.second);
}

template <class T0, class T1, class T2>
void scan(std::tuple<T0, T1, T2> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	scan(t0);
	scan(t1);
	scan(t2);
	p = std::make_tuple(t0, t1, t2);
}

template <class T0, class T1, class T2, class T3>
void scan(std::tuple<T0, T1, T2, T3> &p) {
	T0 t0;
	T1 t1;
	T2 t2;
	T3 t3;
	scan(t0);
	scan(t1);
	scan(t2);
	scan(t3);
	p = std::make_tuple(t0, t1, t2, t3);
}

template <class T>
void scan(std::vector<T> &a) {
	for(auto &i : a) scan(i);
}

void INPUT() {}
template <class Head, class... Tail>
void INPUT(Head &head, Tail &... tail) {
	scan(head);
	INPUT(tail...);
}
}  // namespace scanner
#line 7 "SPJ-Library/template/io.hpp"

#define VEC(type, name, size) \
	vector<type> name(size);  \
	scanner::INPUT(name)
#define VVEC(type, name, h, w)                     \
	vector<vector<type>> name(h, vector<type>(w)); \
	scanner::INPUT(name)
#define INT(...)     \
	int __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LL(...)            \
	long long __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define STR(...)        \
	string __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define CHR(...)      \
	char __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define DBL(...)        \
	double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define LD(...)              \
	long double __VA_ARGS__; \
	scanner::INPUT(__VA_ARGS__)
#define TPL3(type0, type1, type2, name)   \
	std::tuple<type0, type1, type2> name; \
	scanner::INPUT(name);
#define TPL4(type0, type1, type2, type3, name)   \
	std::tuple<type0, type1, type2, type3> name; \
	scanner::INPUT(name);

template <typename T1, typename T2>
std::istream &operator>>(std::istream &is, std::pair<T1, T2> &p) {
	is >> p.first >> p.second;
	return is;
}

template <typename T1, typename T2>
std::ostream &operator<<(std::ostream &os, const std::pair<T1, T2> &p) {
	os << p.first << ' ' << p.second;
	return os;
}

struct fast_io {
	fast_io() {
		std::ios::sync_with_stdio(false);
		std::cin.tie(nullptr);
		std::cout << std::fixed << std::setprecision(15);
		srand((unsigned)time(NULL));
	}
} fast_io_;
#line 2 "SPJ-Library/template/macros.hpp"

#define foa(s, v) for(auto &s : v)
#define sz(v) int(v.size())
#define all(v) (v).begin(), (v).end()
#define rall(v) (v).rbegin(), (v).rend()
#define pcnt(n) __builtin_popcountll((long long)n)

#define REPname(a, b, c, d, e, ...) e
#define rep(...) REPname(__VA_ARGS__, REP3, REP2, REP1, REP0)(__VA_ARGS__)
#define REP0(x) for(int Counter_in_rep_macro = 0; Counter_in_rep_macro < (x); ++Counter_in_rep_macro)
#define REP1(i, x) for(int i = 0; i < (x); ++i)
#define REP2(i, l, r) for(int i = (l); i < (r); ++i)
#define REP3(i, l, r, c) for(int i = (l); i < (r); i += (c))
#define DREPname(a, b, c, d, e, ...) e
#define drep(...) DREPname(__VA_ARGS__, DREP3, DREP2, DREP1)(__VA_ARGS__)
#define DREP1(i, x) for(int i = (x)-1; i >= 0; --i)
#define DREP2(i, l, r) for(int i = (r)-1; i >= (l); --i)
#define DREP3(i, l, r, c) for(int i = (r)-1; i >= (l); i -= (c))

using ll = long long;
using ld = long double;
using ull = unsigned long long;
using vi = std::vector<int>;
using vvi = std::vector<std::vector<int>>;
using vvvi = std::vector<std::vector<std::vector<int>>>;
using vll = std::vector<ll>;
using vvll = std::vector<vll>;
using vvvll = std::vector<vvll>;
template <class T = ll>
using V = std::vector<T>;
template <class T = ll>
using VV = V<V<T>>;
template <class T = ll>
using VVV = V<V<V<T>>>;
template <class T = ll>
using pqmin = std::priority_queue<T, std::vector<T>, std::greater<T>>;
template <class T = ll>
using pqmax = std::priority_queue<T>;
#line 7 "SPJ-Library/template/kuma.hpp"

using namespace std;
#line 9 "a.cpp"

ll solve() {
	auto merge_result = [&](const vvll& a, const vvll& b) -> vvll {
		if(a.empty()) return b;
		if(b.empty()) return a;
		const int n = sz(a) - 1;
		vvll res(n + 1, vll(n + 1, INF));

		vector<vi> split_pos(n + 1, vi(n + 1, -1));

		rep(len, 1, n + 1) {
			rep(left, n) {
				const int right = left + len;
				if(right > n) continue;

				if(len == 1) {
					res[left][right] = 0LL;
					continue;
				}

				if(len == 2) {
					split_pos[left][right] = left + 1;
					res[left][right] = a[left][left + 1] + b[left + 1][right];
					continue;
				}

				int split_leftmost = split_pos[left][right - 1];
				int split_rightmost = split_pos[left + 1][right];

				drep(j, split_leftmost, split_rightmost + 1) {
					if(chmin(res[left][right], a[left][j] + b[j][right])) {
						split_pos[left][right] = j;
					}
				}
			}
		}

		return res;
	};

	INT(s, people, buses);
	vector<ll> x(s);
	for(auto& t : x) cin >> t;

	vector<ll> times;

	rep(people) {
		ll t;
		int p;
		cin >> t >> p;
		p--;
		times.push_back(-(t - x[p]));
	}

	sort(all(times));

	debug(times);

	vector<vll> single(people + 1, vll(people + 1, 0LL));

	rep(left, 0, people) {
		ll cost = 0;
		rep(right, left + 1, people + 1) {
			single[left][right] = cost;
			if(right < people) cost += times[right] - times[left];
		}
	}

	debug(single);

	vvll ans;
	auto& tmp = single;

	while(buses) {
		if(buses & 1) {
			ans = merge_result(ans, tmp);
		}
		tmp = merge_result(tmp, tmp);
		buses >>= 1;
	}

	return ans[0][people];
}

int main() {
	int t = 1;
	rep(t) { print(solve()); }
	return 0;
}
accuracy: 1
time_ms: 730
memory_kb: 113036
final_rank: 16

code_snippet: #line 1 "library/test/aoj/other/2603-SMAWK.test.cpp"
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/problems/2603"
#line 2 "library/other/template.hpp"

#include <bits/stdc++.h>
#line 2 "library/template/macros.hpp"

#line 4 "library/template/macros.hpp"

#ifndef __COUNTER__
#define __COUNTER__ __LINE__
#endif

#define REP_SELECTER(a, b, c, d, e, ...) e
#define REP1_0(b, c) REP1_1(b, c)
#define REP1_1(b, c)                                                           \
    for (ll REP_COUNTER_##c = 0; REP_COUNTER_##c < (ll)(b); ++REP_COUNTER_##c)
#define REP1(b) REP1_0(b, __COUNTER__)
#define REP2(i, b) for (ll i = 0; i < (ll)(b); ++i)
#define REP3(i, a, b) for (ll i = (ll)(a); i < (ll)(b); ++i)
#define REP4(i, a, b, c) for (ll i = (ll)(a); i < (ll)(b); i += (ll)(c))
#define rep(...) REP_SELECTER(__VA_ARGS__, REP4, REP3, REP2, REP1)(__VA_ARGS__)
#define RREP2(i, a) for (ll i = (ll)(a)-1; i >= 0; --i)
#define RREP3(i, a, b) for (ll i = (ll)(a)-1; i >= (ll)(b); --i)
#define RREP4(i, a, b, c) for (ll i = (ll)(a)-1; i >= (ll)(b); i -= (ll)(c))
#define rrep(...) REP_SELECTER(__VA_ARGS__, RREP4, RREP3, RREP2)(__VA_ARGS__)
#define REPS2(i, b) for (ll i = 1; i <= (ll)(b); ++i)
#define REPS3(i, a, b) for (ll i = (ll)(a) + 1; i <= (ll)(b); ++i)
#define REPS4(i, a, b, c) for (ll i = (ll)(a) + 1; i <= (ll)(b); i += (ll)(c))
#define reps(...) REP_SELECTER(__VA_ARGS__, REPS4, REPS3, REPS2)(__VA_ARGS__)
#define RREPS2(i, a) for (ll i = (ll)(a); i > 0; --i)
#define RREPS3(i, a, b) for (ll i = (ll)(a); i > (ll)(b); --i)
#define RREPS4(i, a, b, c) for (ll i = (ll)(a); i > (ll)(b); i -= (ll)(c))
#define rreps(...)                                                             \
    REP_SELECTER(__VA_ARGS__, RREPS4, RREPS3, RREPS2)(__VA_ARGS__)

#define each_for(...) for (auto&& __VA_ARGS__)
#define each_const(...) for (const auto& __VA_ARGS__)

#define all(v) std::begin(v), std::end(v)
#if __cplusplus >= 201402L
#define rall(v) std::rbegin(v), std::rend(v)
#else
#define rall(v) v.rbegin(), v.rend()
#endif

#if __cpp_constexpr >= 201304L
#define CONSTEXPR constexpr
#else
#define CONSTEXPR
#endif

#if __cpp_if_constexpr >= 201606L
#define IF_CONSTEXPR constexpr
#else
#define IF_CONSTEXPR
#endif

#define IO_BUFFER_SIZE 2048
#line 2 "library/template/alias.hpp"

#line 4 "library/template/alias.hpp"

using ll = long long;
using ull = unsigned long long;
using ld = long double;
using PLL = std::pair<ll, ll>;
template<class T>
using prique = std::priority_queue<T, std::vector<T>, std::greater<T>>;

template<class T> class infinity {
public:
    static constexpr T value = std::numeric_limits<T>::max() / 2;
    static constexpr T mvalue = std::numeric_limits<T>::min() / 2;
    static constexpr T max = std::numeric_limits<T>::max();
    static constexpr T min = std::numeric_limits<T>::min();
};

#if __cplusplus <= 201402L
template<class T> constexpr T infinity<T>::value;
template<class T> constexpr T infinity<T>::mvalue;
template<class T> constexpr T infinity<T>::max;
template<class T> constexpr T infinity<T>::min;
#endif

#if __cpp_variable_templates >= 201304L
template<class T> constexpr T INF = infinity<T>::value;
#endif

constexpr ll inf = infinity<ll>::value;
constexpr ld EPS = 1e-8;
constexpr ld PI = 3.1415926535897932384626;
#line 2 "library/template/type_traits.hpp"

#line 5 "library/template/type_traits.hpp"

template<class T, class... Args> struct function_traits_impl {
    using result_type = T;
    template<std::size_t idx>
    using argument_type =
        typename std::tuple_element<idx, std::tuple<Args...>>::type;
    using argument_tuple = std::tuple<Args...>;
    static constexpr std::size_t arg_size() { return sizeof...(Args); }
};

template<class> struct function_traits_helper;

template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...)> {
    using type = function_traits_impl<Res, Args...>;
};
template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...)&> {
    using type = function_traits_impl<Res, Args...>;
};
template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...) const> {
    using type = function_traits_impl<Res, Args...>;
};
template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...) const&> {
    using type = function_traits_impl<Res, Args...>;
};

#if __cpp_noexcept_function_type >= 201510L
template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...) noexcept> {
    using type = function_traits_impl<Res, Args...>;
};
template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...)& noexcept> {
    using type = function_traits_impl<Res, Args...>;
};
template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...) const noexcept> {
    using type = function_traits_impl<Res, Args...>;
};
template<class Res, class Tp, class... Args>
struct function_traits_helper<Res (Tp::*)(Args...) const& noexcept> {
    using type = function_traits_impl<Res, Args...>;
};
#endif

template<class F>
using function_traits =
    typename function_traits_helper<decltype(&F::operator())>::type;


template<class T, class = void> struct is_range : std::false_type {};
template<class T>
struct is_range<
    T,
    decltype(all(std::declval<typename std::add_lvalue_reference<T>::type>()),
             (void)0)> : std::true_type {};

template<class T, bool = is_range<T>::value>
struct range_rank : std::integral_constant<std::size_t, 0> {};
template<class T>
struct range_rank<T, true>
    : std::integral_constant<std::size_t,
                             range_rank<typename T::value_type>::value + 1> {};

template<std::size_t size> struct int_least {
    static_assert(size <= 128, "size must be less than or equal to 128");

    using type = typename std::conditional<
        size <= 8, std::int_least8_t,
        typename std::conditional<
            size <= 16, std::int_least16_t,
            typename std::conditional<
                size <= 32, std::int_least32_t,
                typename std::conditional<size <= 64, std::int_least64_t,
                                          __int128_t>::type>::type>::type>::
        type;
};

template<std::size_t size> using int_least_t = typename int_least<size>::type;

template<std::size_t size> struct uint_least {
    static_assert(size <= 128, "size must be less than or equal to 128");

    using type = typename std::conditional<
        size <= 8, std::uint_least8_t,
        typename std::conditional<
            size <= 16, std::uint_least16_t,
            typename std::conditional<
                size <= 32, std::uint_least32_t,
                typename std::conditional<size <= 64, std::uint_least64_t,
                                          __uint128_t>::type>::type>::type>::
        type;
};

template<std::size_t size> using uint_least_t = typename uint_least<size>::type;

template<class T>
using double_size_int = int_least<std::numeric_limits<T>::digits * 2 + 1>;
template<class T> using double_size_int_t = typename double_size_int<T>::type;
template<class T>
using double_size_uint = uint_least<std::numeric_limits<T>::digits * 2>;
template<class T> using double_size_uint_t = typename double_size_uint<T>::type;

template<class T>
using double_size =
    typename std::conditional<std::is_signed<T>::value, double_size_int<T>,
                              double_size_uint<T>>::type;
template<class T> using double_size_t = typename double_size<T>::type;
#line 2 "library/template/in.hpp"

#line 4 "library/template/in.hpp"
#include <unistd.h>
#line 8 "library/template/in.hpp"

template<std::size_t buf_size = IO_BUFFER_SIZE> class Reader {
private:
    int fd, idx, sz;
    bool state;
    std::array<char, buf_size> buffer;
    inline void read_buf() {
        sz = read(fd, buffer.begin(), buf_size);
        idx = 0;
        if (sz < 0) throw std::runtime_error("input failed");
    }

public:
    static constexpr int get_buf_size() { return buf_size; }
    Reader() noexcept : fd(0), idx(0), sz(0), state(true) {}
    Reader(int fd) noexcept : fd(fd), idx(0), sz(0), state(true) {}
    Reader(FILE* fp) noexcept : fd(fileno(fp)), idx(0), sz(0), state(true) {}

    class iterator {
    private:
        Reader* reader;

    public:
        using difference_type = void;
        using value_type = void;
        using pointer = void;
        using reference = void;
        using iterator_category = std::input_iterator_tag;

        iterator() : reader(nullptr) {}
        explicit iterator(Reader& reader) : reader(&reader) {}
        explicit iterator(Reader* reader) : reader(reader) {}

        iterator& operator++() {
            if (reader->idx == reader->sz) reader->read_buf();
            ++reader->idx;
            return *this;
        }
        iterator operator++(int) {
            iterator res = *this;
            ++(*this);
            return res;
        }
        char operator*() const {
            if (reader->idx == reader->sz) reader->read_buf();
            if (reader->idx < reader->sz) return reader->buffer[reader->idx];
            reader->state = false;
            return '\0';
        }
        bool rdstate() const { return reader->state; }
    };

    iterator begin() noexcept { return iterator(this); }
};

Reader<> reader(0);

template<class Iterator, std::size_t decimal_precision = 16> class Scanner {
public:
    using iterator_type = Iterator;

private:
    template<class, class = void> struct has_scan : std::false_type {};
    template<class T>
    struct has_scan<
        T, decltype(std::declval<T>().scan(std::declval<Scanner&>()), (void)0)>
        : std::true_type {};
    Iterator itr;

public:
    Scanner() = default;
    Scanner(const Iterator& itr) : itr(itr) {}

    char scan_char() {
        char c = *itr;
        ++itr;
        return c;
    }

    Scanner ignore(int n = 1) {
        rep (n) ++itr;
        return *this;
    }

    inline void discard_space() {
        while (('\t' <= *itr && *itr <= '\r') || *itr == ' ') ++itr;
    }
    void scan(char& a) {
        discard_space();
        a = *itr;
        ++itr;
    }
    void scan(bool& a) {
        discard_space();
        a = *itr != '0';
        ++itr;
    }
    void scan(std::string& a) {
        discard_space();
        a.clear();
        while ((*itr < '\t' || '\r' < *itr) && *itr != ' ' && *itr != '\0') {
            a += *itr;
            ++itr;
        }
    }
    template<std::size_t len> void scan(std::bitset<len>& a) {
        discard_space();
        rrep (i, len) {
            a[i] = *itr != '0';
            ++itr;
        }
    }
    template<class T,
             typename std::enable_if<std::is_integral<T>::value &&
                                     !has_scan<T>::value>::type* = nullptr>
    void scan(T& a) {
        discard_space();
        bool sgn = false;
        if IF_CONSTEXPR (std::is_signed<T>::value) {
            if (*itr == '-') {
                sgn = true;
                ++itr;
            }
        }
        a = 0;
        while ('0' <= *itr && *itr <= '9') {
            a = a * 10 + *itr - '0';
            ++itr;
        }
        if IF_CONSTEXPR (std::is_signed<T>::value) {
            if (sgn) a = -a;
        }
    }
    template<class T,
             typename std::enable_if<std::is_floating_point<T>::value &&
                                     !has_scan<T>::value>::type* = nullptr>
    void scan(T& a) {
        discard_space();
        bool sgn = false;
        if (*itr == '-') {
            sgn = true;
            ++itr;
        }
        a = 0;
        while ('0' <= *itr && *itr <= '9') {
            a = a * 10 + *itr - '0';
            ++itr;
        }
        if (*itr == '.') {
            ++itr;
            T n = 0, d = 1;
            for (int i = 0;
                 '0' <= *itr && *itr <= '9' && i < (int)decimal_precision;
                 ++i) {
                n = n * 10 + *itr - '0';
                d *= 10;
                ++itr;
            }
            while ('0' <= *itr && *itr <= '9') ++itr;
            a += n / d;
        }
        if (sgn) a = -a;
    }

private:
    template<std::size_t i, class... Args> void scan(std::tuple<Args...>& a) {
        if IF_CONSTEXPR (i < sizeof...(Args)) {
            scan(std::get<i>(a));
            scan<i + 1, Args...>(a);
        }
    }

public:
    template<class... Args> void scan(std::tuple<Args...>& a) {
        scan<0, Args...>(a);
    }
    template<class T, class U> void scan(std::pair<T, U>& a) {
        scan(a.first);
        scan(a.second);
    }
    template<class T,
             typename std::enable_if<is_range<T>::value &&
                                     !has_scan<T>::value>::type* = nullptr>
    void scan(T& a) {
        each_for (i : a) scan(i);
    }
    template<class T,
             typename std::enable_if<has_scan<T>::value>::type* = nullptr>
    void scan(T& a) {
        a.scan(*this);
    }

    void operator()() {}
    template<class Head, class... Args>
    void operator()(Head& head, Args&... args) {
        scan(head);
        operator()(args...);
    }

    template<class T> Scanner& operator>>(T& a) {
        scan(a);
        return *this;
    }

    explicit operator bool() const { return itr.rdstate(); }
};

Scanner<Reader<>::iterator> scan(reader.begin());

template<class Iterator, std::size_t decimal_precision>
Scanner<Iterator, decimal_precision>&
getline(Scanner<Iterator, decimal_precision>& scan, std::string& a) {
    a.clear();
    char c;
    while ((c = scan.scan_char()) != '\n') {
        a += c;
    }
    return scan;
}
#line 2 "library/template/out.hpp"

#line 8 "library/template/out.hpp"

template<std::size_t buf_size = IO_BUFFER_SIZE> class Writer {
private:
    int fd, idx;
    std::array<char, buf_size> buffer;
    inline void write_buf() {
        int num = write(fd, buffer.begin(), idx);
        idx = 0;
        if (num < 0) throw std::runtime_error("output failed");
    }

public:
    Writer() noexcept : fd(1), idx(0) {}
    Writer(int fd) noexcept : fd(fd), idx(0) {}
    Writer(FILE* fp) noexcept : fd(fileno(fp)), idx(0) {}

    ~Writer() { write_buf(); }

    class iterator {
    private:
        Writer* writer;

    public:
        using difference_type = void;
        using value_type = void;
        using pointer = void;
        using reference = void;
        using iterator_category = std::output_iterator_tag;

        iterator() noexcept : writer(nullptr) {}
        explicit iterator(Writer& writer) noexcept : writer(&writer) {}
        explicit iterator(Writer* writer) noexcept : writer(writer) {}

        iterator& operator++() {
            ++writer->idx;
            if (writer->idx == buf_size) writer->write_buf();
            return *this;
        }
        iterator operator++(int) {
            iterator res = *this;
            ++(*this);
            return res;
        }
        char& operator*() const { return writer->buffer[writer->idx]; }
        void flush() const { writer->write_buf(); }
    };

    iterator begin() noexcept { return iterator(this); }
};

Writer<> writer(1), ewriter(2);

template<class Iterator, bool debug = false> class Printer {
public:
    using iterator_type = Iterator;

private:
    template<class, bool = debug, class = void>
    struct has_print : std::false_type {};
    template<class T>
    struct has_print<T, false,
                     decltype(std::declval<T>().print(std::declval<Printer&>()),
                              (void)0)> : std::true_type {};
    template<class T>
    struct has_print<T, true,
                     decltype(std::declval<T>().debug(std::declval<Printer&>()),
                              (void)0)> : std::true_type {};
    Iterator itr;
    std::size_t decimal_precision;

public:
    void print_char(char c) {
        *itr = c;
        ++itr;
    }

    void flush() { itr.flush(); }

    Printer() noexcept = default;
    explicit Printer(const Iterator& itr) noexcept
        : itr(itr), decimal_precision(16) {}

    void set_decimal_precision(std::size_t decimal_precision) {
        this->decimal_precision = decimal_precision;
    }

    void print(char c) {
        if IF_CONSTEXPR (debug) print_char('\'');
        print_char(c);
        if IF_CONSTEXPR (debug) print_char('\'');
    }
    void print(bool b) { print_char((char)(b + '0')); }
    void print(const char* a) {
        if IF_CONSTEXPR (debug) print_char('"');
        for (; *a != '\0'; ++a) print_char(*a);
        if IF_CONSTEXPR (debug) print_char('"');
    }
    template<std::size_t len> void print(const char (&a)[len]) {
        if IF_CONSTEXPR (debug) print_char('"');
        for (auto i : a) print_char(i);
        if IF_CONSTEXPR (debug) print_char('"');
    }
    void print(const std::string& a) {
        if IF_CONSTEXPR (debug) print_char('"');
        for (auto i : a) print_char(i);
        if IF_CONSTEXPR (debug) print_char('"');
    }
    template<std::size_t len> void print(const std::bitset<len>& a) {
        rrep (i, len) print_char((char)(a[i] + '0'));
    }
    template<class T,
             typename std::enable_if<std::is_integral<T>::value &&
                                     !has_print<T>::value>::type* = nullptr>
    void print(T a) {
        if (!a) {
            print_char('0');
            return;
        }
        if IF_CONSTEXPR (std::is_signed<T>::value) {
            if (a < 0) {
                print_char('-');
                a = -a;
            }
        }
        std::string s;
        while (a) {
            s += (char)(a % 10 + '0');
            a /= 10;
        }
        for (auto i = s.rbegin(); i != s.rend(); ++i) print_char(*i);
    }
    template<class T,
             typename std::enable_if<std::is_floating_point<T>::value &&
                                     !has_print<T>::value>::type* = nullptr>
    void print(T a) {
        if (a == std::numeric_limits<T>::infinity()) {
            print("inf");
            return;
        }
        if (a == -std::numeric_limits<T>::infinity()) {
            print("-inf");
            return;
        }
        if (std::isnan(a)) {
            print("nan");
            return;
        }
        if (a < 0) {
            print_char('-');
            a = -a;
        }
        T b = a;
        if (b < 1) {
            print_char('0');
        }
        else {
            std::string s;
            while (b >= 1) {
                s += (char)('0' + (int)std::fmod(b, 10.0));
                b /= 10;
            }
            for (auto i = s.rbegin(); i != s.rend(); ++i) print_char(*i);
        }
        print_char('.');
        rep (decimal_precision) {
            a *= 10;
            print_char((char)('0' + (int)std::fmod(a, 10.0)));
        }
    }

private:
    template<std::size_t i, class... Args>
    void print(const std::tuple<Args...>& a) {
        if IF_CONSTEXPR (i < sizeof...(Args)) {
            if IF_CONSTEXPR (debug) print_char(',');
            print_char(' ');
            print(std::get<i>(a));
            print<i + 1, Args...>(a);
        }
    }

public:
    template<class... Args> void print(const std::tuple<Args...>& a) {
        if IF_CONSTEXPR (debug) print_char('(');
        if IF_CONSTEXPR (sizeof...(Args) != 0) print(std::get<0>(a));
        print<1, Args...>(a);
        if IF_CONSTEXPR (debug) print_char(')');
    }
    template<class T, class U> void print(const std::pair<T, U>& a) {
        if IF_CONSTEXPR (debug) print_char('(');
        print(a.first);
        if IF_CONSTEXPR (debug) print_char(',');
        print_char(' ');
        print(a.second);
        if IF_CONSTEXPR (debug) print_char(')');
    }
    template<class T,
             typename std::enable_if<is_range<T>::value &&
                                     !has_print<T>::value>::type* = nullptr>
    void print(const T& a) {
        if IF_CONSTEXPR (debug) print_char('{');
        for (auto i = a.begin(); i != a.end(); ++i) {
            if (i != a.begin()) {
                if IF_CONSTEXPR (debug) print_char(',');
                print_char(' ');
            }
            print(*i);
        }
        if IF_CONSTEXPR (debug) print_char('}');
    }
    template<class T, typename std::enable_if<has_print<T>::value &&
                                              !debug>::type* = nullptr>
    void print(const T& a) {
        a.print(*this);
    }
    template<class T, typename std::enable_if<has_print<T>::value &&
                                              debug>::type* = nullptr>
    void print(const T& a) {
        a.debug(*this);
    }

    void operator()() {}
    template<class Head, class... Args>
    void operator()(const Head& head, const Args&... args) {
        print(head);
        operator()(args...);
    }

    template<class T> Printer& operator<<(const T& a) {
        print(a);
        return *this;
    }

    Printer& operator<<(Printer& (*pf)(Printer&)) { return pf(*this); }
};

template<class Iterator, bool debug>
Printer<Iterator, debug>& endl(Printer<Iterator, debug>& pr) {
    pr.print_char('\n');
    pr.flush();
    return pr;
}
template<class Iterator, bool debug>
Printer<Iterator, debug>& flush(Printer<Iterator, debug>& pr) {
    pr.flush();
    return pr;
}

struct SetPrec {
    int n;
    template<class Pr> void print(Pr& pr) const { pr.set_decimal_precision(n); }
    template<class Pr> void debug(Pr& pr) const { pr.set_decimal_precision(n); }
};
SetPrec setprec(int n) { return SetPrec{n}; };

Printer<Writer<>::iterator> print(writer.begin()), eprint(ewriter.begin());

template<class T> auto prints(const T& v) -> decltype(print << v, (void)0) {
    print << v;
    print.print_char('\n');
}

#ifdef SHIO_LOCAL
Printer<Writer<>::iterator, true> debug(writer.begin()),
    edebug(ewriter.begin());
#else
char debug_iterator_character;
class DebugIterator {
public:
    DebugIterator() noexcept = default;
    DebugIterator& operator++() { return *this; }
    DebugIterator& operator++(int) { return *this; }
    char& operator*() const { return debug_iterator_character; }
    void flush() const {}
};
Printer<DebugIterator> debug, edebug;
#endif
#line 2 "library/template/bitop.hpp"

#line 6 "library/template/bitop.hpp"

#line 2 "library/template/func.hpp"

#line 6 "library/template/func.hpp"

#line 2 "library/template/util.hpp"

#line 6 "library/template/util.hpp"

template<class F> class RecLambda {
private:
    F f;

public:
    explicit constexpr RecLambda(F&& f_) : f(std::forward<F>(f_)) {}
    template<class... Args>
    constexpr auto operator()(Args&&... args)
        -> decltype(f(*this, std::forward<Args>(args)...)) {
        return f(*this, std::forward<Args>(args)...);
    }
};

template<class F> inline constexpr RecLambda<F> rec_lambda(F&& f) {
    return RecLambda<F>(std::forward<F>(f));
}

template<class Head, class... Tail> struct multi_dim_vector {
    using type = std::vector<typename multi_dim_vector<Tail...>::type>;
};
template<class T> struct multi_dim_vector<T> { using type = T; };

template<class T, class Arg>
constexpr std::vector<T> make_vec(int n, Arg&& arg) {
    return std::vector<T>(n, std::forward<Arg>(arg));
}
template<class T, class... Args>
constexpr typename multi_dim_vector<Args..., T>::type make_vec(int n,
                                                               Args&&... args) {
    return typename multi_dim_vector<Args..., T>::type(
        n, make_vec<T>(std::forward<Args>(args)...));
}

#line 2 "library/dp/DivideAndConquerOptimization.hpp"

#line 2 "library/dp/SMAWK.hpp"

#line 4 "library/dp/SMAWK.hpp"

template<class F> std::vector<int> smawk(int H, int W, F&& f) {
    std::vector<int> row(H), col(W);
    std::iota(all(row), 0);
    std::iota(all(col), 0);
    return rec_lambda([&](auto&& self, const std::vector<int>& row,
                          const std::vector<int>& col) -> std::vector<int> {
        const int n = row.size();
        if (n == 0) return {};
        std::vector<int> ncol;
        ncol.reserve(n);
        for (int i : col) {
            while (!ncol.empty() && f(row[ncol.size() - 1], ncol.back()) >
                                        f(row[ncol.size() - 1], i))
                ncol.pop_back();
            if ((int)ncol.size() < n) ncol.push_back(i);
        }
        std::vector<int> row_odd;
        row_odd.reserve(n / 2 + 1);
        rep (i, 1, n, 2) row_odd.push_back(row[i]);
        const std::vector<int> ans = self(row_odd, ncol);
        std::vector<int> res(n);
        rep (i, row_odd.size()) res[i * 2 + 1] = ans[i];
        int j = 0;
        rep (i, 0, n, 2) {
            const int last = i == n - 1 ? ncol.back() : res[i + 1];
            res[i] = ncol[j];
            while (ncol[j] < last) {
                ++j;
                if (f(row[i], res[i]) > f(row[i], ncol[j])) res[i] = ncol[j];
            }
        }
        return res;
    })(row, col);
}

/**
 * @brief SMAWK
 * @docs docs/dp/SMAWK.md
 */
#line 5 "library/dp/DivideAndConquerOptimization.hpp"

template<class F>
std::vector<std::vector<typename function_traits<F>::result_type>>
divide_and_conquer_optimization(int m, int n, F&& f) {
    using T = typename function_traits<F>::result_type;
    std::vector<std::vector<T>> dp(m + 1, std::vector<T>(n, INF<T>));
    dp[0][0] = 0;
    rep (i, m) {
        auto g = [&](int x, int y) {
            if (x < y) return INF<T>;
            return dp[i][y] + f(y, x);
        };
        auto res = smawk(n, n, g);
        rep (j, n) dp[i + 1][j] = g(j, res[j]);
    }
    return dp;
}
#line 4 "library/test/aoj/other/2603-SMAWK.test.cpp"
using namespace std;
int main() {
    int s, n, m; scan >> s >> n >> m;
    vector<int> x(s); scan >> x;
    vector<int> t(n);
    rep (i, n) {
        int a, b; scan >> a >> b;
        t[i] = a - x[b - 1];
    }
    sort(all(t));
    vector<int> R(n + 1);
    rep (i, n) R[i + 1] = R[i] + t[i];
    prints(divide_and_conquer_optimization(m, n + 1, [&](int l, int r) {
        return (r - l) * t[r - 1] - (R[r] - R[l]);
    })[m][n]);
}
accuracy: 1
time_ms: 60
memory_kb: 10992
final_rank: 6

code_snippet: #include "bits/stdc++.h"
using namespace std;
using namespace std::chrono;
typedef long long int llint;
typedef long double lldo;
#define mp make_pair
#define mt make_tuple
#define pub push_back
#define puf push_front
#define pob pop_back
#define pof pop_front
#define fir first
#define sec second
#define res resize
#define ins insert
#define era erase
#define REP(i, n) for(int i = 0;i < (n);i++)
/*cout<<fixed<<setprecision(20);cin.tie(0);ios::sync_with_stdio(false);*/
const int mod=1000000007;
const llint inf=2.19e15+1;
const long double pai=3.141592653589793238462643383279502884197;
const long double eps=1e-10;
template <class T,class U>bool chmin(T& a,U b){if(a>b){a=b;return true;}return false;}
template <class T,class U>bool chmax(T& a,U b){if(a<b){a=b;return true;}return false;}
llint gcd(llint a,llint b){if(a%b==0){return b;}else return gcd(b,a%b);}
llint lcm(llint a,llint b){if(a==0){return b;}return a/gcd(a,b)*b;}
template<class T> void SO(T& ve){sort(ve.begin(),ve.end());}
template<class T> void REV(T& ve){reverse(ve.begin(),ve.end());}
template<class T>int LBI(const vector<T>&ar,T in){return lower_bound(ar.begin(),ar.end(),in)-ar.begin();}
template<class T>int UBI(const vector<T>&ar,T in){return upper_bound(ar.begin(),ar.end(),in)-ar.begin();}

//monge dp 分割統治
int main(void){
	int s,n,m,i,j,k;cin>>s>>n>>m;
	vector<llint>x(s);
	for(i=0;i<s;i++){
		cin>>x[i];
	}
	vector<llint>t(n);
	for(i=0;i<n;i++){
		llint ta,pa;
		cin>>ta>>pa;
		t[i]=ta-x[pa-1];
	}
	SO(t);
	//for(i=0;i<n;i++){cerr<<t[i]<<" ";}cerr<<endl;
	vector<llint>wa(n+1);
	for(i=1;i<n;i++){
		wa[i+1]=wa[i]+(t[i]-t[i-1])*i;
	}
	//for(i=0;i<=n;i++){cerr<<wa[i]<<" ";}cerr<<endl;
	
	vector<llint>dp(n+1,inf);
	dp[0]=0;
	for(i=0;i<m;i++){
		vector<llint>ep(n+1,inf);
		vector<int>kaisyu(n+1);//どこから回収したか
		ep[0]=0;
		kaisyu[0]=0;
		{
			pair<llint,int> now=mp(inf,0);
			for(k=0;k<n;k++){
				chmin(now,mp(dp[k]+wa[n]-wa[k]-(t[n-1]-t[k-1])*k,k));
			}
			ep[n]=now.fir;
			kaisyu[n]=now.sec;
		}
		for(int h=11;h>=0;h--){
			int BS=(1<<h);
			for(j=BS;j<n;j+=BS+BS){
				pair<llint,int> now=mp(inf,0);
				for(k=kaisyu[j-BS];k<=min(j-1,kaisyu[min(n,j+BS)]);k++){
					chmin(now,mp(dp[k]+wa[j]-wa[k]-(t[j-1]-t[k-1])*k,k));
				}
				ep[j]=now.fir;
				kaisyu[j]=now.sec;
			}
		}
		
		dp=move(ep);
	}
	cout<<dp[n]<<endl;
	return 0;
}

/*
-10 -1 4

2 3 2
1 15
0 1
5 1
5 2
*/
accuracy: 1
time_ms: 40
memory_kb: 3504
final_rank: 2

code_snippet: //#define _GLIBCXX_DEBUG

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

#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a)  (a).begin(),(a).end()
#define ALLR(a)  (a).rbegin(),(a).rend()
#define UNIQUE(a) (a).erase(unique((a).begin(),(a).end()),(a).end())
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (ll)(m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD1 = 1e9+7;
const ll MOD9 = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T,vector<T>,greater<T>>;
template<typename T1, typename T2>bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;}
template<typename T1, typename T2>bool chmax(T1 &a,T2 b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}  
template<typename T1,typename T2,typename T3>void anss(T1 x,T2 y,T3 z){ans(x!=y,x,z);};  
template<typename T>void debug(const T &v,ll h,ll w,string sv=" "){for(ll i=0;i<h;i++){cout<<v[i][0];for(ll j=1;j<w;j++)cout<<sv<<v[i][j];cout<<endl;}};
template<typename T>void debug(const T &v,ll n,string sv=" "){if(n!=0)cout<<v[0];for(ll i=1;i<n;i++)cout<<sv<<v[i];cout<<endl;};
template<typename T>void debug(const vector<T>&v){debug(v,v.size());}
template<typename T>void debug(const vector<vector<T>>&v){for(auto &vv:v)debug(vv,vv.size());}
template<typename T>void debug(stack<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(queue<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(deque<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop_front();}cout<<endl;}
template<typename T>void debug(PQ<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(QP<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(const set<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T>void debug(const multiset<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T,size_t size>void debug(const array<T, size> &a){for(auto z:a)cout<<z<<" ";cout<<endl;}
template<typename T,typename V>void debug(const map<T,V>&v){for(auto z:v)cout<<"["<<z.first<<"]="<<z.second<<",";cout<<endl;}
template<typename T>vector<vector<T>>vec(ll x, ll y, T w){vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,-1,0,0,1,1,-1,-1};vector<ll>dy={0,0,1,-1,1,-1,1,-1};
template<typename T>vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>auto make_v(size_t a,Ts... ts){return vector<decltype(make_v(ts...))>(a,make_v(ts...));}
template<typename T1, typename T2>ostream &operator<<(ostream &os, const pair<T1, T2>&p){return os << p.first << " " << p.second;}
template<typename T>ostream &operator<<(ostream &os, const vector<T> &v){for(auto &z:v)os << z << " ";cout<<"|"; return os;}
template<typename T>void rearrange(vector<int>&ord, vector<T>&v){
  auto tmp = v;
  for(int i=0;i<tmp.size();i++)v[i] = tmp[ord[i]];
}
template<typename Head, typename... Tail>void rearrange(vector<int>&ord,Head&& head, Tail&&... tail){
  rearrange(ord, head);
  rearrange(ord, tail...);
}
template<typename T> vector<int> ascend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]<v[j];});
  return ord;
}
template<typename T> vector<int> descend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]>v[j];});
  return ord;
}
ll FLOOR(ll n,ll div){assert(div>0);return n>=0?n/div:(n-div+1)/div;}
ll CEIL(ll n,ll div){assert(div>0);return n>=0?(n+div-1)/div:n/div;}
ll digitsum(ll n){ll ret=0;while(n){ret+=n%10;n/=10;}return ret;}
ll modulo(ll n,ll d){return (n%d+d)%d;};
template<typename T>T min(const vector<T>&v){return *min_element(v.begin(),v.end());}
template<typename T>T max(const vector<T>&v){return *max_element(v.begin(),v.end());}
template<typename T>T acc(const vector<T>&v){return accumulate(v.begin(),v.end(),T(0));};
template<typename T>T reverse(const T &v){return T(v.rbegin(),v.rend());};
//mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int popcount(ll x){return __builtin_popcountll(x);};
int poplow(ll x){return __builtin_ctzll(x);};
int pophigh(ll x){return 63 - __builtin_clzll(x);};
template<typename T>T poll(queue<T> &q){auto ret=q.front();q.pop();return ret;};
template<typename T>T poll(priority_queue<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(QP<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(stack<T> &s){auto ret=s.top();s.pop();return ret;};
ll MULT(ll x,ll y){if(LLONG_MAX/x<=y)return LLONG_MAX;return x*y;}
ll POW2(ll x, ll k){ll ret=1,mul=x;while(k){if(mul==LLONG_MAX)return LLONG_MAX;if(k&1)ret=MULT(ret,mul);mul=MULT(mul,mul);k>>=1;}return ret;}
ll POW(ll x, ll k){ll ret=1;for(int i=0;i<k;i++){if(LLONG_MAX/x<=ret)return LLONG_MAX;ret*=x;}return ret;}
template< typename T = int >
struct edge {
  int to;
  T cost;
  int id;
  edge():id(-1){};
  edge(int to, T cost = 1, int id = -1):to(to), cost(cost), id(id){}
  operator int() const { return to; }
};

template<typename T>
using Graph = vector<vector<edge<T>>>;
template<typename T>
Graph<T>revgraph(const Graph<T> &g){
  Graph<T>ret(g.size());
  for(int i=0;i<g.size();i++){
    for(auto e:g[i]){
      int to = e.to;
      e.to = i;
      ret[to].push_back(e);
    }
  }
  return ret;
}
template<typename T>
Graph<T> readGraph(int n,int m,int indexed=1,bool directed=false,bool weighted=false){
  Graph<T> ret(n);
  for(int es = 0; es < m; es++){
    int u,v;
    T w=1;
    cin>>u>>v;u-=indexed,v-=indexed;
    if(weighted)cin>>w;
    ret[u].emplace_back(v,w,es);
    if(!directed)ret[v].emplace_back(u,w,es);
  }
  return ret;
}
template<typename T>
Graph<T> readParent(int n,int indexed=1,bool directed=true){
  Graph<T>ret(n);
  for(int i=1;i<n;i++){
    int p;cin>>p;
    p-=indexed;
    ret[p].emplace_back(i);
    if(!directed)ret[i].emplace_back(p);
  }
  return ret;
}

template<typename T, typename F>
vector<pair<int,T>>smawk(int h, int w,const F &f){
	vector<pair<int,T>>ret(h);
	auto rec=[&](auto &&self,const vector<int>&row,const vector<int>&col)->void{
		if(row.empty())return;
		vector<int>nr,nc;
		for(int i = 1; i < row.size(); i += 2){
			nr.push_back(row[i]);
		}
		for(auto c:col){
			while(!nc.empty() && f(row[nc.size()-1],nc.back()) >= f(row[nc.size()-1],c)){
				nc.pop_back();
			}
			if(nc.size() < row.size()){
				nc.push_back(c);
			}
		}
		self(self,nr,nc);
		int idx = 0;
		for(int i = 0; i < row.size(); i += 2){
			int lim = nc.back();
			if(i + 1 < row.size())lim = ret[row[i + 1]].first;
			ret[row[i]].first = -1;
			while(1){
				T val = f(row[i], nc[idx]);
				if(ret[row[i]].first == -1 || ret[row[i]].second > val){
					ret[row[i]] = make_pair(nc[idx], val);
				}
				if(nc[idx]==lim)break;
				idx++;
			}
		}
	};
	vector<int>row(h),col(w);
	iota(row.begin(),row.end(),0);
	iota(col.begin(),col.end(),0);
	rec(rec,row,col);
	return ret;
}
template<typename T, typename F>
vector<pair<int,T>>monotone_minima(int h, int w,const F &f){
	vector<pair<int,T>>ret(h);
	auto dc=[&](auto &&self,int xl,int xr,int yl,int yr)->void{
		if(xl >= xr)return;
		int mid = (xl + xr) / 2;
		ret[mid].first = -1;
		for(int y = yl; y < yr; y++){
			T val = f(mid,y);
			if(ret[mid].first == -1 || ret[mid].second > val){
				ret[mid] = make_pair(y,val);
			}
		}
		self(self,xl,mid,yl,ret[mid].first+1);
		self(self,mid+1,xr,ret[mid].first,yr);
	};
	dc(dc,0,h,0,w);
	return ret;
}
int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  ll res=0,buf=0;
  bool judge = true;
	ll s,n,m;cin>>s>>n>>m;
	vector<ll>x(s);
	rep(i,0,s)cin>>x[i];
	vector<ll>t(n);
	rep(i,0,n){
		ll a,b;cin>>a>>b;b--;
		t[i]=a-x[b];
	}
	sort(ALL(t));
	vector<ll>c(n+1);
	rep(i,0,n)c[i+1]=c[i]+t[i];
	vector<ll>dp(n+1,INF);
	dp[0]=0;
	rep(_,0,m){
		auto cost=[&](ll r,ll l)->ll{
			if(r<l)return INF;
			if(l==r)return dp[l];
			return (r-l)*t[r-1]-(c[r]-c[l])+dp[l];
		};
		auto minima=monotone_minima<ll>(n+1,n+1,cost);
		rep(i,0,n+1)dp[i]=minima[i].se;
	}
	cout<<dp[n]<<endl;
  return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 3552
final_rank: 3

code_snippet: //#define _GLIBCXX_DEBUG

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

#define endl '\n'
#define lfs cout<<fixed<<setprecision(10)
#define ALL(a)  (a).begin(),(a).end()
#define ALLR(a)  (a).rbegin(),(a).rend()
#define UNIQUE(a) (a).erase(unique((a).begin(),(a).end()),(a).end())
#define spa << " " <<
#define fi first
#define se second
#define MP make_pair
#define MT make_tuple
#define PB push_back
#define EB emplace_back
#define rep(i,n,m) for(ll i = (n); i < (ll)(m); i++)
#define rrep(i,n,m) for(ll i = (ll)(m) - 1; i >= (ll)(n); i--)
using ll = long long;
using ld = long double;
const ll MOD1 = 1e9+7;
const ll MOD9 = 998244353;
const ll INF = 1e18;
using P = pair<ll, ll>;
template<typename T> using PQ = priority_queue<T>;
template<typename T> using QP = priority_queue<T,vector<T>,greater<T>>;
template<typename T1, typename T2>bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;}
template<typename T1, typename T2>bool chmax(T1 &a,T2 b){if(a<b){a=b;return true;}else return false;}
ll median(ll a,ll b, ll c){return a+b+c-max({a,b,c})-min({a,b,c});}
void ans1(bool x){if(x) cout<<"Yes"<<endl;else cout<<"No"<<endl;}
void ans2(bool x){if(x) cout<<"YES"<<endl;else cout<<"NO"<<endl;}
void ans3(bool x){if(x) cout<<"Yay!"<<endl;else cout<<":("<<endl;}
template<typename T1,typename T2>void ans(bool x,T1 y,T2 z){if(x)cout<<y<<endl;else cout<<z<<endl;}  
template<typename T1,typename T2,typename T3>void anss(T1 x,T2 y,T3 z){ans(x!=y,x,z);};  
template<typename T>void debug(const T &v,ll h,ll w,string sv=" "){for(ll i=0;i<h;i++){cout<<v[i][0];for(ll j=1;j<w;j++)cout<<sv<<v[i][j];cout<<endl;}};
template<typename T>void debug(const T &v,ll n,string sv=" "){if(n!=0)cout<<v[0];for(ll i=1;i<n;i++)cout<<sv<<v[i];cout<<endl;};
template<typename T>void debug(const vector<T>&v){debug(v,v.size());}
template<typename T>void debug(const vector<vector<T>>&v){for(auto &vv:v)debug(vv,vv.size());}
template<typename T>void debug(stack<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(queue<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(deque<T> st){while(!st.empty()){cout<<st.front()<<" ";st.pop_front();}cout<<endl;}
template<typename T>void debug(PQ<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(QP<T> st){while(!st.empty()){cout<<st.top()<<" ";st.pop();}cout<<endl;}
template<typename T>void debug(const set<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T>void debug(const multiset<T>&v){for(auto z:v)cout<<z<<" ";cout<<endl;}
template<typename T,size_t size>void debug(const array<T, size> &a){for(auto z:a)cout<<z<<" ";cout<<endl;}
template<typename T,typename V>void debug(const map<T,V>&v){for(auto z:v)cout<<"["<<z.first<<"]="<<z.second<<",";cout<<endl;}
template<typename T>vector<vector<T>>vec(ll x, ll y, T w){vector<vector<T>>v(x,vector<T>(y,w));return v;}
ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;}
vector<ll>dx={1,-1,0,0,1,1,-1,-1};vector<ll>dy={0,0,1,-1,1,-1,1,-1};
template<typename T>vector<T> make_v(size_t a,T b){return vector<T>(a,b);}
template<typename... Ts>auto make_v(size_t a,Ts... ts){return vector<decltype(make_v(ts...))>(a,make_v(ts...));}
template<typename T1, typename T2>ostream &operator<<(ostream &os, const pair<T1, T2>&p){return os << p.first << " " << p.second;}
template<typename T>ostream &operator<<(ostream &os, const vector<T> &v){for(auto &z:v)os << z << " ";cout<<"|"; return os;}
template<typename T>void rearrange(vector<int>&ord, vector<T>&v){
  auto tmp = v;
  for(int i=0;i<tmp.size();i++)v[i] = tmp[ord[i]];
}
template<typename Head, typename... Tail>void rearrange(vector<int>&ord,Head&& head, Tail&&... tail){
  rearrange(ord, head);
  rearrange(ord, tail...);
}
template<typename T> vector<int> ascend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]<v[j];});
  return ord;
}
template<typename T> vector<int> descend(const vector<T>&v){
  vector<int>ord(v.size());iota(ord.begin(),ord.end(),0);
  sort(ord.begin(),ord.end(),[&](int i,int j){return v[i]>v[j];});
  return ord;
}
ll FLOOR(ll n,ll div){assert(div>0);return n>=0?n/div:(n-div+1)/div;}
ll CEIL(ll n,ll div){assert(div>0);return n>=0?(n+div-1)/div:n/div;}
ll digitsum(ll n){ll ret=0;while(n){ret+=n%10;n/=10;}return ret;}
ll modulo(ll n,ll d){return (n%d+d)%d;};
template<typename T>T min(const vector<T>&v){return *min_element(v.begin(),v.end());}
template<typename T>T max(const vector<T>&v){return *max_element(v.begin(),v.end());}
template<typename T>T acc(const vector<T>&v){return accumulate(v.begin(),v.end(),T(0));};
template<typename T>T reverse(const T &v){return T(v.rbegin(),v.rend());};
//mt19937 mt(chrono::steady_clock::now().time_since_epoch().count());
int popcount(ll x){return __builtin_popcountll(x);};
int poplow(ll x){return __builtin_ctzll(x);};
int pophigh(ll x){return 63 - __builtin_clzll(x);};
template<typename T>T poll(queue<T> &q){auto ret=q.front();q.pop();return ret;};
template<typename T>T poll(priority_queue<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(QP<T> &q){auto ret=q.top();q.pop();return ret;};
template<typename T>T poll(stack<T> &s){auto ret=s.top();s.pop();return ret;};
ll MULT(ll x,ll y){if(LLONG_MAX/x<=y)return LLONG_MAX;return x*y;}
ll POW2(ll x, ll k){ll ret=1,mul=x;while(k){if(mul==LLONG_MAX)return LLONG_MAX;if(k&1)ret=MULT(ret,mul);mul=MULT(mul,mul);k>>=1;}return ret;}
ll POW(ll x, ll k){ll ret=1;for(int i=0;i<k;i++){if(LLONG_MAX/x<=ret)return LLONG_MAX;ret*=x;}return ret;}
template< typename T = int >
struct edge {
  int to;
  T cost;
  int id;
  edge():id(-1){};
  edge(int to, T cost = 1, int id = -1):to(to), cost(cost), id(id){}
  operator int() const { return to; }
};

template<typename T>
using Graph = vector<vector<edge<T>>>;
template<typename T>
Graph<T>revgraph(const Graph<T> &g){
  Graph<T>ret(g.size());
  for(int i=0;i<g.size();i++){
    for(auto e:g[i]){
      int to = e.to;
      e.to = i;
      ret[to].push_back(e);
    }
  }
  return ret;
}
template<typename T>
Graph<T> readGraph(int n,int m,int indexed=1,bool directed=false,bool weighted=false){
  Graph<T> ret(n);
  for(int es = 0; es < m; es++){
    int u,v;
    T w=1;
    cin>>u>>v;u-=indexed,v-=indexed;
    if(weighted)cin>>w;
    ret[u].emplace_back(v,w,es);
    if(!directed)ret[v].emplace_back(u,w,es);
  }
  return ret;
}
template<typename T>
Graph<T> readParent(int n,int indexed=1,bool directed=true){
  Graph<T>ret(n);
  for(int i=1;i<n;i++){
    int p;cin>>p;
    p-=indexed;
    ret[p].emplace_back(i);
    if(!directed)ret[i].emplace_back(p);
  }
  return ret;
}

template<typename T, typename F>
vector<pair<int,T>>smawk(int h, int w,const F &f){
	vector<pair<int,T>>ret(h);
	auto rec=[&](auto &&self,const vector<int>&row,const vector<int>&col)->void{
		if(row.empty())return;
		vector<int>nr,nc;
		for(int i = 1; i < row.size(); i += 2){
			nr.push_back(row[i]);
		}
		for(auto c:col){
			while(!nc.empty() && f(row[nc.size()-1],nc.back()) >= f(row[nc.size()-1],c)){
				nc.pop_back();
			}
			if(nc.size() < row.size()){
				nc.push_back(c);
			}
		}
		self(self,nr,nc);
		int idx = 0;
		for(int i = 0; i < row.size(); i += 2){
			int lim = nc.back();
			if(i + 1 < row.size())lim = ret[row[i + 1]].first;
			ret[row[i]].first = -1;
			while(1){
				T val = f(row[i], nc[idx]);
				if(ret[row[i]].first == -1 || ret[row[i]].second > val){
					ret[row[i]] = make_pair(nc[idx], val);
				}
				if(nc[idx]==lim)break;
				idx++;
			}
		}
	};
	vector<int>row(h),col(w);
	iota(row.begin(),row.end(),0);
	iota(col.begin(),col.end(),0);
	rec(rec,row,col);
	return ret;
}
template<typename T, typename F>
vector<pair<int,T>>monotone_minima(int h, int w,const F &f){
	vector<pair<int,T>>ret(h);
	auto dc=[&](auto &&self,int xl,int xr,int yl,int yr)->void{
		if(xl >= xr)return;
		int mid = (xl + xr) / 2;
		ret[mid].first = -1;
		for(int y = yl; y < yr; y++){
			T val = f(mid,y);
			if(ret[mid].first == -1 || ret[mid].second > val){
				ret[mid] = make_pair(y,val);
			}
		}
		self(self,xl,mid,yl,ret[mid].first+1);
		self(self,mid+1,xr,ret[mid].first,yr);
	};
	dc(dc,0,h,0,w);
	return ret;
}
int main(){
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  ll res=0,buf=0;
  bool judge = true;
	ll s,n,m;cin>>s>>n>>m;
	vector<ll>x(s);
	rep(i,0,s)cin>>x[i];
	vector<ll>t(n);
	rep(i,0,n){
		ll a,b;cin>>a>>b;b--;
		t[i]=a-x[b];
	}
	sort(ALL(t));
	vector<ll>c(n+1);
	rep(i,0,n)c[i+1]=c[i]+t[i];
	vector<ll>dp(n+1,INF);
	dp[0]=0;
	rep(_,0,m){
		auto cost=[&](ll r,ll l)->ll{
			if(r<l)return INF;
			if(l==r)return dp[l];
			return (r-l)*t[r-1]-(c[r]-c[l])+dp[l];
		};
		auto minima=smawk<ll>(n+1,n+1,cost);
		rep(i,0,n+1)dp[i]=minima[i].se;
	}
	cout<<dp[n]<<endl;
  return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 3588
final_rank: 4

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=1000000007,MAX=2005;
const ll INF=1LL<<60;
pair<ll,ll> dp[MAX];

int main(){
    
    std::ifstream in("text.txt");
    std::cin.rdbuf(in.rdbuf());
    cin.tie(0);
    ios::sync_with_stdio(false);
    
    int S,N,K;cin>>S>>N>>K;
    vector<int> x(S);
    for(int i=0;i<S;i++) cin>>x[i];
    vector<int> A(N);
    for(int i=0;i<N;i++){
        int t,a;cin>>t>>a;
        a--;
        A[i]=t-x[a];
    }
    sort(all(A));
    
    ll left=-1,right=1LL<<30;
    ll ans=0;
    while(right-left>1){
        ll mid=(left+right)/2;
        for(int i=0;i<=N;i++) dp[i]=mp(-INF,-INF);
        dp[0]=mp(0,0);
        for(int i=1;i<=N;i++){
            ll sum=0;
            for(int j=i-1;j>=0;j--){
                sum+=A[i-1]-A[j];
                chmax(dp[i],mp(dp[j].fi-sum-mid,dp[j].se+1));
            }
        }
        if(dp[N].se>=K){
            left=mid;
            ans=dp[N].fi+(mid*K);
        }else{
            right=mid;
        }
    }
    
    ans*=(-1);
    
    cout<<ans<<endl;
}
accuracy: 1
time_ms: 90
memory_kb: 3512
final_rank: 5

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>
using namespace std;

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

typedef unsigned long long ul;
typedef unsigned int ui;
const ll mod = 998244353;
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;
typedef long double ld;
typedef pair<ld, ld> LDP;
const ld eps = 1e-8;
const ld pi = acosl(-1.0);

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;
	ll res = 1;
	while (n) {
		if (n & 1)res = res * x % m;
		x = x * x % m; n >>= 1;
	}
	return res;
}
struct modint {
	ll n;
	modint() :n(0) { ; }
	modint(ll m) :n(m) {
		if (n >= mod)n %= mod;
		else if (n < 0)n = (n % mod + mod) % mod;
	}
	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 << 2;
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];
}

struct uf {
private:
	vector<int> par, ran;
public:
	uf(int n) {
		par.resize(n, 0);
		ran.resize(n, 0);
		rep(i, n) {
			par[i] = i;
		}
	}
	int find(int x) {
		if (par[x] == x)return x;
		else return par[x] = find(par[x]);
	}
	void unite(int x, int y) {
		x = find(x), y = find(y);
		if (x == y)return;
		if (ran[x] < ran[y]) {
			par[x] = y;
		}
		else {
			par[y] = x;
			if (ran[x] == ran[y])ran[x]++;
		}
	}
	bool same(int x, int y) {
		return find(x) == find(y);
	}
};

int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };

struct CHT {
	vector<LP> v;
	vector<LP> memo;
	int l=0;
	bool check(LP a, LP b, LP c) {
		return (b.first - a.first) * (c.second - b.second) >= (b.second - a.second) * (c.first - b.first);
	}
	void add(LP a) {
		while (v.size() >= 2 && check(v[v.size() - 2], v[v.size() - 1], a))v.pop_back();
		v.push_back(a);
	}
	//xは単調増加
	ll f(LP a, ll x) {
		return a.first * x + a.second;
	}
	ll query(ll x) {
		while (l >= v.size())l--;
		while (l + 1 < v.size() && f(v[l], x) > f(v[l + 1], x))l++;
		return f(v[l], x);
	}
};

void solve() {
	//s,n,m -> n,m,k
	int n, m, k; cin >> n >> m >> k;
	vector<int> x(n);
	rep(i, n)cin >> x[i];
	vector<int> ts;
	rep(i, m) {
		int t, p; cin >> t >> p;
		p--;
		ts.push_back(t - x[p]);
	}
	sort(all(ts));
	vector<ll> rt(m + 1);
	rep(i, m)rt[i + 1] = rt[i] + ts[i];
	vector<ll> dp(m + 1, INF);
	dp[0] = 0;
	rep(_, k) {
		vector<ll> ndp(m + 1, INF);
		CHT cht;
		ndp[0] = 0;
		rep(i, m+1) {
			if (dp[i] < INF) {
				LP p = { -i,dp[i] + rt[i] };
				cht.add(p);
			}
			if (i > 0) {
				ll val = cht.query(ts[i-1]);
				val += i * ts[i-1] - rt[i];
				ndp[i] = val;
			}
			//cout << i << " " << val << "\n";
		}
		swap(dp, ndp);
	}
	cout << dp[m] << "\n";
}



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