Problem:
あみだくじ
問題
あなたは J 君と一緒にあみだくじを使って遊んでいる.あみだくじは
n
本の縦棒と
m
本の横棒からなる.縦棒には左から順に 1 から
n
の番号がついており,縦棒
i
の下端には正整数
s
i
が書かれている.
図 3-1 あみだくじの例(
n
= 4,
m
= 5,
s
1
= 20,
s
2
= 80,
s
3
= 100,
s
4
= 50)
縦棒
i
の一番上から順に道をたどっていき到達した下端に書かれている整数が, 縦
棒
i
を選んだ場合の得点である.例えば,図 3-1 では,縦棒 1 を選ぶと得点は 80 点
であり,縦棒 2 を選ぶと得点は 100 点である.
図 3-2 道のたどり方の例
J 君は縦棒 1 から縦棒
k
までの連続した
k
本を選ぶことにした.それら
k
本の縦棒を選んだときの点数の合計が J 君の得点となる.ただし,あなたはあみだくじ内の
横棒を一本選び,その横棒をあみだくじから削除することができる. (削除しなくてもよい.) もし,あなたが横棒を一本削除した場合は,削除後のあみだくじにおいて,
縦棒 1 から縦棒
k
までの連続した
k
本の縦棒を選んだときの点数の合計が J 君の得点となる.
入力としてあみだくじの形と J 君の選ぶ縦棒の本数
k
が与えられたとき,J 君の得
点の最小値を求めるプログラムを作成せよ.
入力
入力は複数のデータセットからなる．各データセットは以下の形式で与えられる．
1 行目には 4 つの整数
n
,
m
,
h
,
k
が空白区切りで書かれている.
n
(2 ≤
n
≤ 1000) は縦棒の本数を,
m
(1 ≤
m
≤ 100000) は横棒の本数を,
h
(2 ≤
h
≤ 1000) は縦棒の長さを,
k
(1 ≤
k
≤ n) は J 君が選ぶ縦棒の本数を表す.
続く
n
行には縦棒の下端に書かれている点数が書かれている.
i
+ 1 行目 (1 ≤
i
≤ n)には正整数
s
i
が書かれている. また,
s
1
+
s
2
+ ... +
s
n
≤ 2000000000 = 2 × 10
9
を満たす.
続く
m
行には横棒の位置が書かれている.横棒には 1 から
m
までの番号がついている.
i
+
n
+ 1 行目 (1 ≤
i
≤
m
) には, 横棒
i
の位置を表す 2 つの整数
a
i
,
b
i
(1 ≤
a
i
≤
n
- 1, 1 ≤
b
i
≤
h
- 1) が空白区切りで書かれており,横棒
i
が縦棒
a
i
と縦棒
a
i
+ 1 を結び, 横棒
i
の上端からの距離が
b
i
であることを表す. ただし,どの 2 つの横棒も端点を共有することはない.
採点用データのうち,配点の 20 % 分は横棒を削除しない場合に J 君の得点が最少となる.また,配点の 30 % 分は
n
≤ 20,
m
≤ 30,
h
≤  10 を満たし,配点の 60 % 分は
m
≤ 1000 を満たす.
入力の終わりは 4つのゼロを含む行で示される. データセットの数は 10 を超えない．
出力
データセットごとに, J 君の得点の最小値を1 行に出力する.
入出力例
入力例
4 5 7 2
20
80
100
50
1 1
2 6
2 3
1 5
3 1
2 2 5 1
10
20
1 1
1 3
0 0 0 0
出力例
100
10
1つ目の例 は図 3-1 に対応し,あなたが横棒 4 (縦棒 1 と縦棒 2 を上端から距離 5 の場所で結ぶ横棒)を削除したとき,J 君の得点は最小になる.例 2 では,あなたが横棒を削除しない場合に J 君の得点が最小になる. (図3-3 を見よ.)
図 3-3
上記問題文と自動審判に使われるデータは、
情報オリンピック日本委員会
が作成し公開している問題文と採点用テストデータです。

Submitted solutions:

code_snippet: /* ---------- STL Libraries ---------- */
// IO library
#include <cstdio>

#include <fstream>
#include <iomanip>
#include <ios>
#include <iostream>

// algorithm library
#include <algorithm>

#include <cmath>
#include <numeric>
#include <random>
#include <cstring>
#include <cassert>

// container library
#include <array>
#include <bitset>
#include <deque>
#include <map>
#include <unordered_map>
#include <queue>
#include <set>
#include <string>
#include <tuple>
#include <vector>
#include <stack>

// type
#include <cstdint>

/* ---------- Namespace ---------- */
using namespace std;

/* ---------- Type ---------- */
using ll = long long;
#define int ll
#define P pair<ll, ll>

/* ---------- Constants  */
const double PI = 3.141592653589793238462643383279;
const ll MOD = 1e9 + 7;
const int INF = 1LL << 55;

bool solve() {
    int N, M, H, K;
    cin >> N >> M >> H >> K;
    if (!(N || M || H || K)) return false;
    vector<int> goals(N);
    for (int i = 0; i < N; i++) cin >> goals[i];

    vector<P> bars(M); // <height, left>
    for (int i = 0; i < M; i++) {
        int a, b;
        cin >>a >> b;
        bars[i].first = b;
        bars[i].second = a - 1;
    }
    sort(bars.begin(), bars.end());

    vector<int> players(N);
    for (int i = 0; i < N; i++) players[i] = i;

    vector<P> bar_swaps(M);
    for (int i = 0; i < M; i++) {
        int left = bars[i].second;
        int right = bars[i].second + 1;
        bar_swaps[i].first = players[left];
        bar_swaps[i].second = players[right];
        swap(players[left], players[right]);
    }

    vector<int> results(N);
    for (int i = 0; i < N; i++) {
        results[players[i]] = goals[i];
    }

    int mn = 1;
    for (int i = 0; i < M; i++) {
        int left = bar_swaps[i].first;
        int right = bar_swaps[i].second;
        if (left > right) swap(left, right);
        if (left < K && right >= K) {
            mn = min(mn, results[right] - results[left]);
        }
    }

    int sum = 0;
    for (int i = 0; i < K; i++) sum += results[i];
    if (mn < 0) sum += mn;

    cout << sum << endl;
    return true;
}

signed main() {
    while (true) {
        bool ret = solve();
        if (!ret) break;
    }
}
accuracy: 1
time_ms: 30
memory_kb: 6028
final_rank: 15

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    int n, m, h, k;
    while (true) {
        cin >> n >> m >> h >> k;
        if (n == 0 && m == 0 && h == 0 && k == 0) {
            break;
        }
        vector<int> c(n), st(n), ans(n);
        vector<pair<int, int>> a(m, {0, 0}), s;

        for (int i = 0; i < n; i++) {
            cin >> c[i];
            st[i] = i;
        }
        for (int i = 0; i < m; i++) {
            int x, y;
            cin >> x >> y;
            a[i] = {y, x - 1};
        }
        sort(a.begin(), a.end());
        for (int i = 0; i < m; i++) {
            s.push_back({st[a[i].second], st[a[i].second + 1]});
            swap(st[a[i].second], st[a[i].second + 1]);
        }
        for (int i = 0; i < n; i++) {
            ans[st[i]] = c[i];
        }

        int mx = 0;
        for (int i = 0; i < m; i++) {
            int x = min(s[i].first, s[i].second), y = max(s[i].first, s[i].second);
            if (y >= k && x < k) {
                mx = max(mx, ans[x] - ans[y]);
            }
        }

        int sm = 0;
        for (int i = 0; i < k; i++) {
            sm += ans[i];
        }
        cout << sm - mx << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 4848
final_rank: 11

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll=long long;
int main(){
    ll N,M,H,K;
    while(cin>>N>>M>>H>>K,N+M!=0){
    vector<ll> S(N);
    for(int i=0;i<N;i++)cin>>S[i];
    vector<pair<ll,ll>> F(M);
    for(int i=0;i<M;i++)cin>>F[i].second>>F[i].first;
    sort(F.begin(),F.end());
    vector<int> P(N);
    for(int i=0;i<N;i++)P[i]=i;
    vector<pair<int,int>> SW(M);
    for(int i=0;i<M;i++){
        int a=F[i].second;
        SW[i]={P[a],P[a-1]};
        swap(P[a],P[a-1]);
    }
    vector<ll> T(N);
    for(int i=0;i<N;i++)T[P[i]]=S[i];
    ll an=0,bn=0;
    for(int i=0;i<K;i++)bn+=T[i];
    an=bn;
    for(int i=0;i<M;i++){
        int u=SW[i].first;
        int v=SW[i].second;
        if(u>v)swap(u,v);
        if(u<K&&v>=K){
            an=min(an,bn-T[u]+T[v]);
        }
    }
    cout<<an<<endl;
    
}}
accuracy: 1
time_ms: 30
memory_kb: 5324
final_rank: 12

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int main() {
    while(true) {
        int n = in(), m = in(), h = in(), k = in(); if(n == 0) return 0;
        vector<int> s = in(n);

        vector<pair<int,int>> e(m); // height, swap(i, i + 1)
        for(auto &[a, b] : e) {
            a = in(), b = in();
            tie(a, b) = make_pair(b, a - 1);
        }
        sort(e);
        
        vector<pair<int,int>> f;
        vector<int> p = iota(n);
        for(auto [_, i] : e) {
            f.push_back({p[i], p[i + 1]});
            swap(p[i], p[i + 1]);
        }

        int sum = [&] {
            int res = 0;
            for(int i : rep(n)) if(p[i] < k) res += s[i];
            return res;
        }();

        vector<int> t(n, -1);
        for(int i : rep(n)) t[p[i]] = s[i];

        int mi = 0;
        for(auto [i, j] : f) {
            if(i < k and k <= j) chmin(mi, t[j] - t[i]);
            if(j < k and k <= i) chmin(mi, t[i] - t[j]);
        }
        print(sum + mi);
    }
}
accuracy: 1
time_ms: 10
memory_kb: 4880
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define all(a) a.begin(),a.end()
#define reps(i, a, n) for (int i = (a); i < (int)(n); i++)
#define rep(i, n) reps(i, 0, n)
#define rreps(i, a, n) for (int i = (a); i > (int)(n); i--)
const long long mod = 1000000007;
const long long INF = 1e18;

ll n,m,h,k;

void solve() {
 vector<ll> score (n);
 vector<ll> start (n);
 rep(i,n) {
   start[i] = i;
 }
 set<pair<int,int>> change;
 vector<ll> g (n);
 rep(i,n) {
   cin >> g[i];
 }
 
 vector<pair<int,int>> yoko (m);
 rep(i,m) {
   cin >> yoko[i].second >> yoko[i].first;
 }
 sort(all(yoko));
 
 rep(i,m) {
   swap(start[yoko[i].second-1],start[yoko[i].second]);
   change.insert({start[yoko[i].second-1],start[yoko[i].second]});
 }
 vector<ll> ans (n);
 rep(i,n) {
   ans[start[i]] = g[i];
 }
 
 vector<ll> rr (n+1,0);
 rep(i,n) {
   rr[i+1] = rr[i] + ans[i];
 }
 ll mn = INF;
 mn = min(mn,rr[0+k]-rr[0]);
 for (auto w : change) {
   swap(ans[w.first],ans[w.second]);
   rr[0] = 0;
   rep(i,n) {
     rr[i+1] = rr[i] + ans[i];
   }
   mn = min(mn,rr[k]-rr[0]);
   swap(ans[w.first],ans[w.second]);
 }
 cout << mn << endl;
 return;
}

int main() {
  while (true) {
    cin >> n >> m >> h >> k;
    if (n == 0) {
      return 0;
    }
    solve();
  }
}
accuracy: 1
time_ms: 50
memory_kb: 5140
final_rank: 17

code_snippet: // (⁠◕⁠ᴗ⁠◕⁠✿⁠)

#include <bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i, n) for (ll i = 0; i < (n); i++)
#define srep(i, s, n) for (ll i = s; i < (n); i++)
#define len(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
using namespace std;
template<typename T> using vc = vector<T>;
template<typename T> using vv = vc<vc<T>>;
template<typename T> using vvv = vv<vc<T>>;
using vi = vc<int>;using vvi = vv<int>; using vvvi = vv<vi>;
using ll = long long;using vl = vc<ll>;using vvl = vv<ll>; using vvvl = vv<vl>;
using ld = long double; using vld = vc<ld>; using vvld = vc<vld>; using vvvld = vc<vvld>;
using uint = unsigned int;
using ull = unsigned long long;
const ld pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
// const ll mod = 1000000007;
const ll mod = 998244353;
inline bool inside(ll y, ll x, ll H, ll W) {return 0 <= (y) and (y) < (H) and 0 <= (x) and (x) < (W); }

#define debug(var)  do{std::cout << #var << " : \n";view(var);}while(0)
template<typename T> void view(T e){cout << e << endl;}
template<typename T> void view(const vc<T>& v){for(const auto& e : v){ cout << e << " "; } cout << endl;}
template<typename T> void view(const vv<T>& vv){ for(const auto& v : vv){ view(v); } }

ll solve(int N, int M, int H, int K){
    vl S(N); rep(i, N) cin >> S[i];
    vc<set<int>> toR(H), toL(H);
    map<pair<int, int>, int> toid;
    rep(i, M){
        int a, b; cin >> a >> b; a--;
        toR[b].insert(a);
        toL[b].insert(a + 1);
        toid[{b, a}] = i;
    }
    vi use(N, 0), goal(N); rep(i, K) use[i] = 1;
    // debug(use);
    vi L(M, -1), R(M, -1);
    rep(i, N){
        int p = i;
        rep(h, H){
            if (toR[h].count(p)){
                R[toid[{h, p}]] = i;
                p++;
            }else if (toL[h].count(p)){
                p--;
                L[toid[{h, p}]] = i;
            }
        }
        goal[i] = p;
    }
    // debug(goal);
    // debug(L);
    // debug(R);
    ll ans = 0, tmp;
    rep(i, N) if (use[i]) ans += S[goal[i]];
    tmp = ans;
    rep(i, M){
        // cout << L[i] << " " << R[i] << endl;
        if (use[L[i]] && !use[R[i]]) ans = min(ans, tmp - S[goal[L[i]]] + S[goal[R[i]]]);
        if (!use[L[i]] && use[R[i]]) ans = min(ans, tmp - S[goal[R[i]]] + S[goal[L[i]]]);
        // cout << ans << endl;
    }
    return ans;
}

int main(){
    vl ans;
    while (true){
        int N, M, H, K; cin >> N >> M >> H >> K;
        if (N == 0) break;
        ans.push_back(solve(N, M, H, K));
    }
    for (auto x : ans) cout << x << endl;
}
accuracy: 1
time_ms: 240
memory_kb: 19564
final_rank: 20

code_snippet: #include<bits/stdc++.h>
using namespace std;
int main() {
  while (1) {
    int n, m, h, k;
    cin >> n >> m >> h >> k;
    if (!n && !m && !h && !k) break;
    vector<int> s(n);
    for (int i = 0; i < n; i++) {
      cin >> s[i];
    }
    vector<pair<int, int>> ab(m);
    for (int i = 0; i < m; i++) {
      int a, b;
      cin >> a >> b;
      a--;
      ab[i] = make_pair(b, a);
    }
    sort(ab.begin(), ab.end());
    vector<int> R(n);//R[下] = 上
    iota(R.begin(), R.end(), 0);
    for (int i = 0; i < m; i++) {
      int a = ab[i].second;
      swap(R[a], R[a + 1]);
    }
    vector<int> P(n);//P[上] = 下
    long long Sum = 0;

    for (int i = 0; i < n; i++) {
      if (R[i] < k) {//下の番号に対して，上がk未満の時Sumに加算
        Sum += s[i];
      }
      P[R[i]] = i;
    }
    vector<int> c(n);
    iota(c.begin(), c.end(), 0);//更新しながら見ていくと，c[結んでいる棒の番号] = 上
    long long MIN = 0;
    for (int i = 0; i < m; i++) {
      int a = ab[i].second;
      //P[c[a]]はc[a]が消す棒の左側から上にたどっていったときの棒の番号であるから，棒を消さなかったとき左側から入り，たどり着く下の番号
      //棒を消すとP[c[a]]とP[c[a + 1]]が入れ替わる。
      //c[a]とc[a + 1]のどちらかが[0, k)の時，棒を消すとスコアの和が変化する。
      if (c[a] < k && c[a + 1] >= k) {
        long long tmp = -s[P[c[a]]] + s[P[c[a + 1]]];
        MIN = min(MIN, tmp);
      }
      if (c[a] >= k && c[a + 1] < k) {
        long long tmp = s[P[c[a]]] - s[P[c[a + 1]]];
        MIN = min(MIN, tmp);
      }      
      swap(c[a], c[a + 1]);
    }
    long long ans = Sum + MIN;
    cout << ans << endl;
  }
}
accuracy: 1
time_ms: 30
memory_kb: 3828
final_rank: 5

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef pair<int, int> Pi;
int main(){
    int n, m, h, k, a, b, s[1010], tate[1010], po[1010];
    while(cin >> n >> m >> h >> k, n){
        vector<Pi> vec;
        for(int i=1;i<=n;i++) cin >> s[i];
        for(int i=0;i<m;i++){
            cin >> a >> b;
            vec.push_back(Pi(b, a));
        }
        sort(vec.begin(), vec.end());
        for(int i=1;i<=n;i++) tate[i] = i;
        vector<Pi> pa;
        for(int i=0;i<vec.size();i++){
            pa.push_back(Pi(tate[vec[i].second], tate[vec[i].second+1]));
            swap(tate[vec[i].second], tate[vec[i].second+1]);
        }
        int sum = 0;
        for(int i=1;i<=n;i++){
            po[tate[i]] = s[i];
            if(tate[i]<=k) sum += s[i];
        }
        int ans = sum;
        for(int i=0;i<pa.size();i++){
            if(pa[i].first<=k && pa[i].second>k) ans = min(ans, sum-po[pa[i].first]+po[pa[i].second]);
            if(pa[i].first>k && pa[i].second<=k) ans = min(ans, sum-po[pa[i].second]+po[pa[i].first]);
        }
        cout << ans << endl;
    }
    return(0);
}
accuracy: 1
time_ms: 40
memory_kb: 5124
final_rank: 13

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<long double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    int n,m,h,k;
    while (cin >> n >> m >> h >> k, k) {
        vector<int> a(n);
        for (int i = 0; i < n; i++) {
            cin >> a[i];
        }
        vector<pair<int,int>> v;
        for (int i = 0; i < m; i++) {
            int a,b; cin >> a >> b;
            a--;
            v.push_back({b, a});
        }
        sort(v.begin(), v.end());
        vector<int> to(n);
        for (int i = 0; i < n; i++) {
            to[i] = i;
        }
        vector<pair<int,int>> u;
        for (auto p : v) {
            int i = p.second;
            u.push_back({to[i], to[i+1]});
            swap(to[i], to[i+1]);
        }
        vector<int> id(n);
        for (int i = 0; i < n; i++) {
            id[to[i]] = i;
        }
        ll sum = 0;
        for (int i = 0; i < k; i++) {
            sum += a[id[i]];
        }
        ll res = sum;
        for (auto p : u) {
            if ((p.first < k) != (p.second < k)) {
                if (p.first < k) {
                    res = min(res, sum-a[id[p.first]]+a[id[p.second]]);
                }
                else {
                    swap(p.first, p.second);
                    res = min(res, sum-a[id[p.first]]+a[id[p.second]]);
                }
            }
        }
        cout << res << "\n";
    }
    
}
accuracy: 1
time_ms: 10
memory_kb: 5344
final_rank: 8

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vl = vector<ll>;
using vvl = vector<vl>;
using pl = pair<ll,ll>;
using vp = vector<pl>;
#define rep(i,n) for(ll i=0;i<(ll)(n);++i)
#define reps(i,s,n) for(ll i=(s);i<(ll)(n);++i)
#define rep1(i,n) for(ll i=1;i<=(ll)(n);++i)
template<typename T>inline bool chmax(T &a,T b){return a<b?a=b,true:false;}
template<typename T>inline bool chmin(T &a,T b){return a>b?a=b,true:false;}
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define be(v) (v).begin(),(v).end()
const long long INF = 1e18;
#ifdef DEBUG
#include <debug.hpp>
random_device rd;
mt19937 gen(rd());
ll random(ll l,ll h){
	uniform_int_distribution<ll> dist(l,h);
	return dist(gen);
}
#endif

ll N,M,H,K;
vl S;
vector<vp> A;
#ifdef DEBUG
void showall(){
	show(N,M,H,K,S);show(A);
}
#endif
bool input(){
	#ifdef DEBUG
	show("input");
	#endif
	cin>>N>>M>>H>>K;
	if(N==0)return false;
	S.assign(N,0);
	rep(n,N)cin>>S.at(n);
	A.assign(N,vp(0));
	//A.assign(N,vp);
	rep(m,M){
		ll a,b;cin>>a>>b;--a;
		A.at(a).eb(b,1);
		A.at(a+1).eb(b,-1);
	}
	rep(n,N){
		sort(be(A.at(n)));
	}
	#ifdef DEBUG
	showall();
	#endif
	return true;
}
void logic(){
#ifdef DEBUG
show("logic");
#endif
	vl G(N);
	map<pl,pl> mp;
	rep(n,N){
		ll h=0,p=n;
		while(true){
	#ifdef DEBUG
			show("n h p",n,h,p);
	#endif
			auto it = lower_bound(be(A.at(p)),pl(h+1,-INF));
			if(it == A.at(p).end()){
				G.at(n) = S.at(p);break;
			}
			pl z; 
			if(it->se == -1) z={p-1,it->fi};
			else z={p,it->fi};
			if(mp.count(z)){
				if(mp[z].fi > n){
					mp[z].se = mp[z].fi;
					mp[z].fi = n;
				}else{
					mp[z].se = n;
				}
			}
			else mp[z].fi = n;
			h = it->fi;
			p += it->se;
		}
	}
	#ifdef DEBUG
	show("G",G);show("mp",mp);
	#endif
	ll mx=0,ans=0;
	for(auto e:mp){
		ll x = e.se.fi, y = e.se.se;
		if(x < K && y >= K){
			if(G.at(x) > G.at(y)){
				chmax(mx, G.at(x) - G.at(y));
			}
		}
	}
	rep(n,K){
		ans += G.at(n);
	}
	cout<< ans - mx <<endl;
}
#ifdef DEBUG
ll naive(){
	return 1;
}
#endif
int main(){
	while(input())logic();
	#ifdef DEBUG
	//show("naive=",naive());
	#endif
	#ifdef DEBUG
	/*
	rep(q,100){
		N=random(1LL,1000LL);
		ll lans=logic(),nans=naive();
		showall();
		if(lans!=nans){ show(" WA",lans,nans); break; }
		else{ show(" AC",lans,nans); }
	}
	*/
	#endif
	return 0;
}
//cout << fixed << setprecision(9);
accuracy: 1
time_ms: 80
memory_kb: 15044
final_rank: 19

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)

template<class T>
using vi = vector<T>;

template<class T>
using vii = vector<vi<T>>;

template<class T>
using viii = vector<vii<T>>;

using pii = pair<int, int>;

int main()
{
    int n, m, h, k;
    while(cin >> n >> m >> h >> k, n + m + h + k){
        vi<int> score(n);
        map<int, vi<int>> mp;
        rep(i, n) cin >> score[i];
        rep(i, m) {
            int a, b;
            cin >> a >> b;
            a--;
            mp[b].push_back(a);
        }
    
        vi<int> idx(n);
        rep(i, n) idx[i] = i;
    
        set<pii> st;
        for (auto elem : mp) {
            for (int v : elem.second) {
                st.insert({ idx[v], idx[v + 1] });
                swap(idx[v], idx[v + 1]);
            }
        }
        
        vi<int> pos(n);
        rep(i, n) pos[idx[i]] = score[i];
        int acum = 0;
        rep(i, k) acum += pos[i];
    
        int ans = acum;
        for (pii elem : st) {
            if (elem.first < k && elem.second < k) continue;
            if (elem.first >= k && elem.second >= k) continue;
            if (elem.first > elem.second) swap(elem.first, elem.second);
            ans = min(ans, acum + pos[elem.second] - pos[elem.first]);
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 5284
final_rank: 14

code_snippet: //#include <atcoder/all>
#include <bits/stdc++.h>
using namespace std;
using lint = long long;
constexpr lint mod = 1e9 + 7;
#define all(x) begin(x), end(x)
#define bitcount(n) __builtin_popcountll((lint)(n))
#define fcout cout << fixed << setprecision(15)
#define highest(x) (63 - __builtin_clzll(x))
#define rep(i, n) for(int i = 0; i < int(n); i++)
#define rep2(i, l, r) for(int i = int(l); i < int(r); i++)
#define repr(i, n) for(int i = int(n) - 1; i >= 0; i--)
#define repr2(i, l, r) for(int i = int(r) - 1; i >= int(l); i--)
constexpr int inf9 = 1e9; constexpr lint inf18 = 1e18;
inline void Yes(bool condition){ if(condition) cout << "Yes" << endl; else cout << "No" << endl; }
template<class itr> void array_output(itr start, itr goal){ for(auto i = start; i != goal; i++) cout << (i == start ? "" : " ") << (*i); cout << endl; }
template<class itr> void cins(itr first, itr last){ for(auto i = first; i != last; i++){ cin >> (*i); } }
template<class T> T gcd(T a, T b){ if(b) return gcd(b, a % b); else return a; }
template<class T> T lcm(T a, T b){ return a / gcd(a, b) * b; }
template<class T> bool chmax(T &a, const T &b){ if(a < b){ a = b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b){ if(b < a){ a = b; return 1; } return 0; }
inline int has(lint i, int j){ return (i >> j) & 1; }
int dy[4] = {1, 0, -1, 0}; int dx[4] = {0, 1, 0, -1};
bool is_inside(lint y, lint x, lint H, lint W){ return (0 <= y && y < H && 0 <= x && x < W); }

struct io_init {
    io_init() {
        cin.tie(nullptr); cout.tie(nullptr);
        std::ios::sync_with_stdio(false);
    }
} io_init;

void solve(){
    int n, m, h, k;
    cin >> n >> m >> h >> k;
    if(n == 0) exit(0);
    
    lint s[n];
    rep(i, n) cin >> s[i];
    
    vector<pair<int, int>> bars;
    rep(_, m){
        int a, b;
        cin >> a >> b;
        a--, b--;
        bars.push_back({b, a});
    }
    
    sort(all(bars));
    
    vector<bool> chosen(n, false);
    rep(i, k) chosen[i] = true;
    for(auto [b, a]: bars){
        swap(chosen[a], chosen[a + 1]);
    }
    
    lint score = 0;
    rep(i, n){
        if(chosen[i]) score += s[i];
    }
    
    vector<int> goal(n);
    rep(i, n) goal[i] = i;
    reverse(all(bars));
    lint min_diff = 0;
    for(auto [b, a]: bars){
        if(chosen[goal[a]] != chosen[goal[a + 1]]){
            if(chosen[goal[a]]){
                chmin(min_diff, s[goal[a + 1]] - s[goal[a]]);
            }else{
                chmin(min_diff, s[goal[a]] - s[goal[a + 1]]);
            }
        }
        swap(goal[a], goal[a + 1]);
    }
    
    cout << score + min_diff << endl;
}

int main(){
    while(true) solve();
}
accuracy: 1
time_ms: 10
memory_kb: 4080
final_rank: 1

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef pair< int , int > Pi;

int main(){
  int n, m, h, k, s[1000];
  Pi ab[100000], c[100000], d[100000];
  int ans[1000], pos[1000];

  while(scanf("%d %d %d %d", &n, &m, &h, &k), n){
    for(int i = 0; i < n; i++){
      scanf("%d", &s[i]);
      ans[i] = i;
    }
    for(int i = 0; i < m; i++){
      scanf("%d %d", &ab[i].second, &ab[i].first);
    }
    sort( ab, ab + m);
  
    int base = 0;
    for(int i = 0; i < m; i++){
      swap(ans[ab[i].second - 1], ans[ab[i].second]);
      d[i] = Pi( ans[ab[i].second - 1], ans[ab[i].second]);
    }
    for(int i = 0; i < n; i++){
      if(ans[i] < k) base += s[i];
      pos[ans[i]] = i;
    }

    int ret = base;

    for(int i = 0; i < m; i++){
      int res = base;
      
      if(d[i].first < k && d[i].second >= k){
        res -= s[pos[d[i].first]];
        res += s[pos[d[i].second]];
      }
      if(d[i].second < k && d[i].first >= k){
      res += s[pos[d[i].first]];
      res -= s[pos[d[i].second]];
      }
      ret = min( res, ret);
    }
    
    cout << ret << endl;
  }  
}
accuracy: 1
time_ms: 20
memory_kb: 5516
final_rank: 10

code_snippet: #include <bits/stdc++.h>
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define drep(i,j,n) for(int i=0;i<(int)(n-1);i++)for(int j=i+1;j<(int)(n);j++)
#define trep(i,j,k,n) for(int i=0;i<(int)(n-2);i++)for(int j=i+1;j<(int)(n-1);j++)for(int k=j+1;k<(int)(n);k++)
#define codefor int test;scanf("%d",&test);while(test--)
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define yes(ans) if(ans)printf("yes\n");else printf("no\n")
#define Yes(ans) if(ans)printf("Yes\n");else printf("No\n")
#define YES(ans) if(ans)printf("YES\n");else printf("NO\n")
#define popcount(v) __builtin_popcount(v)
#define vector2d(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define vector3d(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
using namespace std;
using ll = long long;
template<class T> using rpriority_queue = priority_queue<T, vector<T>, greater<T>>;
const int MOD=1000000007;
const int MOD2=998244353;
const int INF=1<<30;
const ll INF2=1LL<<60;
void scan(int& a){scanf("%d",&a);}
void scan(long long& a){scanf("%lld",&a);}
template<class T,class L>void scan(pair<T, L>& p){scan(p.first);scan(p.second);}
template<class T,class U,class V>void scan(tuple<T,U,V>& p){scan(get<0>(p));scan(get<1>(p));scan(get<2>(p));}
template<class T, size_t size> void scan(array<T, size>& a){ for(auto&& i : a) scan(i);}
template<class T> void scan(T& a){cin>>a;}
template<class T> void scan(vector<T>& vec){for(auto&& it:vec)scan(it);}
void in(){}
template <class Head, class... Tail> void in(Head& head, Tail&... tail){scan(head);in(tail...);}
void print(const int& a){printf("%d",a);}
void print(const long long& a){printf("%lld",a);}
void print(const double& a){printf("%.15lf",a);}
template<class T,class L>void print(const pair<T, L>& p){print(p.first);putchar(' ');print(p.second);}
template<class T> void print(const T& a){cout<<a;}
template<class T> void print(const vector<T>& vec){if(vec.empty())return;print(vec[0]);for(auto it=vec.begin();++it!= vec.end();){putchar(' ');print(*it);}}
void out(){putchar('\n');}
template<class T> void out(const T& t){print(t);putchar('\n');}
template <class Head, class... Tail> void out(const Head& head,const Tail&... tail){print(head);putchar(' ');out(tail...);}
template<class T> void dprint(const T& a){cerr<<a;}
template<class T> void dprint(const vector<T>& vec){if(vec.empty())return;cerr<<vec[0];for(auto it=vec.begin();++it!= vec.end();){cerr<<" "<<*it;}}
void debug(){cerr<<endl;}
template<class T> void debug(const T& t){dprint(t);cerr<<endl;}
template <class Head, class... Tail> void debug(const Head& head, const Tail&... tail){dprint(head);cerr<<" ";debug(tail...);}
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
ll modpow(ll a, ll b, ll p){ ll ans = 1; while(b){ if(b & 1) (ans *= a) %= p; (a *= a) %= p; b /= 2; } return ans; }
ll modinv(ll a, ll m) {ll b = m, u = 1, v = 0;while (b) {ll t = a / b;a -= t * b; swap(a, b);u -= t * v; swap(u, v);}u %= m;if (u < 0) u += m;return u;}
ll updivide(ll a,ll b){return (a+b-1)/b;}
template<class T> void chmax(T &a,const T b){if(b>a)a=b;}
template<class T> void chmin(T &a,const T b){if(b<a)a=b;}

int main(){
    while(1){
    INT(n,m,h,k);
    if(n==0)return 0;
    vector<ll> sc(n);
    in(sc);
    vector<vector<int>> t(h);
    vector<vector<int>> g(n);
    int u,v;
    rep(i,m){
        in(u,v);
        t[--v].push_back(--u);
    }
    vector<int> pos(n);
    iota(all(pos),0);
    for(auto vec:t){
        for(auto x:vec){
            g[pos[x]].push_back(pos[x+1]);
            g[pos[x+1]].push_back(pos[x]);
            swap(pos[x],pos[x+1]);
        }
    }
    vector<ll> a(n),sumv(n+1,0);
    rep(i,n)a[pos[i]]=sc[i];
    rep(i,n)sumv[i+1]=sumv[i]+a[i];
    ll ans=INF2;
    chmin(ans,sumv[k]-sumv[0]);
    for(int i=0;i<k;i++){
        for(auto x:g[i]){
            if(x<k)continue;
            chmin(ans,sumv[k]-sumv[0]-a[i]+a[x]);
        }
    }
    out(ans);
    }
}
accuracy: 1
time_ms: 10
memory_kb: 5068
final_rank: 4

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using lli = long long int;

int main(){
    while(1){
        int n,m,h,k;
        cin >> n >> m >> h >> k;
        if(n == 0) break;

        vector<int> a(n);
        for(int i=0; i<n; i++){
            cin >> a[i];
        }
        vector<pair<int,int>> bar(m);
        for(int i=0; i<m; i++){
            cin >> bar[i].second >> bar[i].first;
            bar[i].second--;
        }
        sort(bar.begin(), bar.end());
        vector<int> curr(n);
        for(int i=0; i<n; i++){
            curr[i] = i;
        }
        vector<pair<int,int>> swp(m);
        for(int i=0; i<m; i++){
            swp[i] = {curr[bar[i].second], curr[bar[i].second +1]};
            swap(curr[bar[i].second], curr[bar[i].second +1]);
        }
        vector<int> score(n);
        for(int i=0; i<n; i++){
            score[curr[i]] = a[i];
        }
        int sum = 0;
        for(int i=0; i<k; i++){
            sum += score[i];
        }
        int ans = sum;
        for(int i=0; i<m; i++){
            int a = swp[i].first;
            int b = swp[i].second;
            if(a > b) swap(a, b);
            if(a<k and b>=k){
                ans = min(ans, sum-score[a]+score[b]);
            }
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 4584
final_rank: 9

code_snippet: #include <bits/stdc++.h>
using namespace std; typedef long long ll; typedef pair <ll, ll> P;

#define dbg(x) true;
#define vdbg(x) true;
#define vvdbg(x) true;
#define pdbg(x) true;
#define vpdbg(x) true;
#define spdbg(x) true;
int main() {cin.tie(0); ios::sync_with_stdio(false); 
	while(true){
		ll n,m,h,k; cin >> n >> m >> h >>k;
		if (n == 0) break;
		vector<ll>  a(n), aa(n), bb(n), c(n);
		for( ll i = 0 ; i <  n ; i++ ){
			cin >> a[i];
			aa[i] = i;
			bb[i] = i;
		}
		vector<P> p(m);
		vdbg(a);

		for( ll i = 0 ; i <  m ; i++ ){
			cin >> p[i].first >> p[i].second;
			p[i].first --;
		}
		sort(p.begin(),p.end(), [&](P a,    P b) -> bool { return a.second < b.second;});
		pdbg(p);
		for( ll i = 0 ; i <  m ; i++ ){
			swap(aa[p[i].first+1], aa[p[i].first]);
		}
		for( ll i = 0 ; i <  n ; i++ ){
			c[aa[i]] = a[i];
		}
		vdbg(c);
		ll ans = 0;
		vector<bool> flag(n,false); 

		for( ll i = 0 ; i <  n ; i++ ){
			if(aa[i] < k) {
				dbg(a[i]);
				ans += a[i];
				flag[i] = true;
			}
		}
		vdbg(aa);	vdbg(flag);

		ll tmp = 0; 
		for( ll i = 0 ; i <  m ; i++ ){
			ll x = bb[p[i].first+1], y = bb[p[i].first];
			dbg(x) ; dbg(y);
			if (( x < k) && (k <= y) ){
				tmp = min( tmp, c[y]-c[x]);
				dbg(c[y]-c[x]);
			}
			if ( (k <= x) && (y < k) ){
				tmp = min( tmp, c[x]-c[y]);
				dbg(c[x]-c[y]);
			}
			swap(bb[p[i].first+1], bb[p[i].first]);
			
		}
		dbg(tmp); dbg(ans);
		cout << ans +tmp << endl;
	}
	return 0;
}

// 80 100 50 20
accuracy: 1
time_ms: 10
memory_kb: 4320
final_rank: 2

code_snippet: #include<cstdio>
#include<algorithm>
using namespace std;
typedef pair<int,int>P;
P p[100001];
int a[1001],y[100001],z[100001],ans[1001]={0};
int main(void)
{
	int n,m,h,k,i,b,c,j,x,mn,sum=0,sum2;
	while(1){
		scanf("%d%d%d%d",&n,&m,&h,&k);
		if(n==0)	break;
		for(i=1;i<=n;i++)	scanf("%d",&a[i]);
		for(i=1;i<=m;i++){
			scanf("%d%d",&b,&c);
			p[i].first=c;	p[i].second=b;
		}
		sort(p+1,p+m+1);
		for(i=1;i<=n;i++){
			x=i;
			for(j=1;j<=m;j++){
				if(p[j].second==x){
					y[j]=i;
					x++;
				}
				else if(p[j].second==x-1){
					z[j]=i;
					x--;
				}
			}
			ans[i]=a[x];
		}
		/*for(i=1;i<=n;i++)	printf("%d ",ans[i]);
		printf("\n");
		for(i=1;i<=m;i++)	printf("%d %d\n",y[i],z[i]);
		printf("\n");*/
		sum=0;
		for(i=1;i<=k;i++)	sum+=ans[i];
		mn=sum;
		for(i=1;i<=m;i++){
			sum2=sum;
			if(y[i]<=k)		sum2+=ans[z[i]]-ans[y[i]];
			if(z[i]<=k)		sum2+=ans[y[i]]-ans[z[i]];
			mn=min(mn,sum2);
		}
		printf("%d\n",mn);
	}
	return 0;
}
accuracy: 1
time_ms: 60
memory_kb: 4268
final_rank: 16

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

int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  
  sss:
  int n, m, h, k;
  cin >> n >> m >> h >> k;
  if (n + m + h + k == 0) return 0;
  
  vector<int> score(n);
  for (int i = 0; i < n; i++) cin >> score.at(i);
  
  vector<pair<int, int>> x(m);
  for (int i = 0; i < m; i++) {
    cin >> x.at(i).second >> x.at(i).first;
    x.at(i).first *= -1;
  }
  
  sort(x.begin(), x.end());
  
  vector<int> order(n);
  for (int i = 0; i < n; i++) order.at(i) = i;
  
  vector<pair<int, int>> swap_p(m);
  for (int i = 0; i < m; i++) {
    swap_p.at(i).second = order.at(x.at(i).second);
    swap_p.at(i).first = order.at(x.at(i).second - 1);
    swap(order.at(x.at(i).second), order.at(x.at(i).second - 1));
  }
  
  set<int> st;
  int keep = 0;
  for (int i = 0; i < k; i++) {
    keep += score.at(order.at(i));
    st.insert(order.at(i));
  }
  
  int ans = keep;
  for (int i = 0; i < m; i++) {
    if (st.find(swap_p.at(i).first) == st.end() && st.find(swap_p.at(i).second) != st.end()) {
      ans = min(ans, keep - score.at(swap_p.at(i).second) + score.at(swap_p.at(i).first));
    }
    if (st.find(swap_p.at(i).first) != st.end() && st.find(swap_p.at(i).second) == st.end()) {
      ans = min(ans, keep + score.at(swap_p.at(i).second) - score.at(swap_p.at(i).first));
    }
  }
  
  cout << ans << '\n';
  goto sss;
}
accuracy: 1
time_ms: 20
memory_kb: 4600
final_rank: 7

code_snippet: #include<bits/stdc++.h>
#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#define rep(i, x) for(ll i = 0; i < x; i++)
#define rep2(i, x) for(ll i = 1; i <= x; i++)
#define all(a) (a).begin(),(a).end()
using ll = long long;
using ld = long double;
using namespace std;
const ll INF = 1000000000;
const int intINF = 1000000000;
const ll mod = 1000000007;
const ll MOD = 998244353;
const ld pi = 3.141592653589793238;

typedef pair <ll, ll> P;
ll dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 };

ll n, m, h, k;//縦棒の本数、横棒の本数、縦の長さ、選ぶ本数

vector<ll> ten(1002);
vector<P> sa(100002, P(0, 0));
vector<vector<ll>> aru(100002, vector<ll>(2, 0));
vector<vector<P>> leng(1002);
ll dfs(ll tate, ll yoko, ll start) {
	//cout << tate << ' ' << yoko << endl;
	//にぶたん1回目
	ll ok = -1, ng = leng[yoko].size(), mid = (ok + ng) / 2;
	while (ng - ok > 1) {
		if (leng[yoko][mid].first > tate) { ng = mid; }
		else { ok = mid; }
		mid = (ok + ng) / 2;
	}
	ok++;
	ll a = leng[yoko][ok].first, b = leng[yoko][ok].second;
	//cout << a << ' ' << b << endl;
	//にぶたん二回目
	ok = -1, ng = leng[yoko - 1].size(), mid = (ok + ng) / 2;
	while (ng - ok > 1) {
		if (leng[yoko - 1][mid].first > tate) { ng = mid; }
		else { ok = mid; }
		mid = (ok + ng) / 2;
	}
	ok++;
	if (leng[yoko - 1][ok].first < a) {
		a = leng[yoko - 1][ok].first; b = leng[yoko - 1][ok].second;
		if (a == h) { return ten[yoko]; }
		yoko--;
		if (start <= k) { aru[b][1] = 1; }
		return sa[b].second = dfs(a, yoko, start);
	}
	else {
		if (a == h) { /*cout << tate << endl;*/ return ten[yoko]; }
		yoko++;
		if (start <= k) { aru[b][0] = 1; }
		return sa[b].first = dfs(a, yoko, start);
	}
	//終わり
}
signed main() {
	ios::sync_with_stdio(false);
	std::cin.tie(nullptr);
	//cout << fixed << setprecision(15);

	while (true) {
		cin >> n >> m >> h >> k;
		if (n == 0 && m == 0) { break; }
		rep2(i, n) { cin >> ten[i]; }
		rep(i, m) {
			ll a, b; cin >> a >> b;
			leng[a].push_back(P(b, i));
		}
		leng[0].push_back(P(h, 0));
		rep2(i, n) { leng[i].push_back(P(h, 0)); sort(all(leng[i])); }
		ll ans = 0;
		rep2(i, n) {//あみだくじを前から
			ll uio = dfs(0, i, i);
			if (i <= k) { ans += uio; }
			//cout << uio << endl;
		}
		//削除
		ll cnt = 0;
		rep(i, m) {
			if (aru[i][0] == 1 && aru[i][1] == 1) { continue; }
			if (aru[i][0] == 1) {
				cnt = max(cnt, sa[i].first - sa[i].second);
			}
			if (aru[i][1] == 1) {
				cnt = max(cnt, sa[i].second - sa[i].first);
			}
		}
		cout << ans - cnt << endl;
		rep(i, m) {
			rep(j, 2) {
				aru[i][j] = 0;
			}
		}
		rep(i, n + 2) { leng[i].clear(); }
	}
	return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 12032
final_rank: 18

code_snippet: #include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> transform(int N, vector<int> arr, vector<int> perm) {
	vector<int> res(N);
	for (int i = 0; i < N; ++i) {
		res[i] = arr[perm[i]];
	}
	return res;
}
int main() {
	cin.tie(0);
	ios_base::sync_with_stdio(false);
	while (true) {
		int N, M, H, K;
		cin >> N >> M >> H >> K;
		if (N == 0 && M == 0 && H == 0 && K == 0) break;
		vector<int> S(N), A(M), B(M);
		for (int i = 0; i < N; ++i) {
			cin >> S[i];
		}
		for (int i = 0; i < M; ++i) {
			cin >> A[i] >> B[i]; --A[i];
		}
		vector<int> perm(M);
		for (int i = 0; i < M; ++i) {
			perm[i] = i;
		}
		sort(perm.begin(), perm.end(), [&](int i, int j) { return B[i] < B[j]; });
		A = transform(M, A, perm);
		B = transform(M, B, perm);
		vector<int> p(N);
		for (int i = 0; i < N; ++i) {
			p[i] = i;
		}
		vector<int> lc(M), rc(M);
		for (int i = 0; i < M; ++i) {
			lc[i] = p[A[i]];
			rc[i] = p[A[i] + 1];
			swap(p[A[i]], p[A[i] + 1]);
		}
		int maxdiff = 0;
		for (int i = M - 1; i >= 0; --i) {
			swap(S[A[i]], S[A[i] + 1]);
			if (lc[i] < K && rc[i] >= K) {
				maxdiff = max(maxdiff, S[A[i]] - S[A[i] + 1]);
			}
			if (lc[i] >= K && rc[i] < K) {
				maxdiff = max(maxdiff, S[A[i] + 1] - S[A[i]]);
			}
		}
		int score = 0;
		for (int i = 0; i < K; ++i) {
			score += S[i];
		}
		cout << score - maxdiff << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 5240
final_rank: 6