/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 768.0 KiB
#2 Accepted 18ms 884.0 KiB
#3 Accepted 28ms 568.0 KiB
#4 Accepted 22ms 588.0 KiB
#5 Accepted 23ms 1.0 MiB
#6 Accepted 46ms 4.988 MiB
#7 Accepted 58ms 25.328 MiB
#8 Accepted 60ms 25.289 MiB
#9 Accepted 62ms 25.449 MiB
#10 Accepted 59ms 25.27 MiB
#11 Accepted 60ms 25.566 MiB
#12 Accepted 60ms 25.391 MiB

Code

#ifndef LOCAL
#include <bits/stdc++.h>
#define debug(...)
#endif

using namespace std;
#define int long long
#define sz(v) (int)(v).size()
#define cinv(v) for (auto &it:v) cin>>it;
#define coutv(v) for (auto &it:v) cout<< it<<' '; cout<<'\n';

template<typename T, T (*op)(T, T), T (*op2)(T, T)> struct SparseTable {
    vector<vector<T> > t, t2;

    SparseTable(const vector<T> &v): t(1, v), t2(1, v) {
        int K = __lg(sz(v)), N = sz(v);
        for (int i = 1; i <= K; ++i) {
            t.emplace_back(sz(v) - (1 << i) + 1);
            t2.emplace_back(sz(v) - (1 << i) + 1);
            for (int j = 0; j + (1 << i) <= N; ++j) {
                t[i][j] = op(t[i - 1][j], t[i - 1][j + (1 << (i - 1))]);
                t2[i][j] = op2(t2[i - 1][j], t2[i - 1][j + (1 << (i - 1))]);
            }
        }
    }

    T query(int L, int R, bool f) {
        assert(L<=R);
        int i = __lg(R - L + 1);
        return f ? op(t[i][L], t[i][R - (1 << i) + 1]) : op2(t2[i][L], t2[i][R - (1 << i) + 1]);
    }
};

int op(int a, int b) { return min(a, b); }
int op2(int a, int b) { return max(a, b); }

const int INF = 1e12;

void shelby() {
    int n, k;
    cin >> n >> k;
    vector<int> v(n + 1);
    for (int i = 1; i <= n; ++i) cin >> v[i];
    SparseTable<int, op, op2> table(v);
    int ans = INF, now = 0;
    for (int i = 1; i <= k; ++i) now += v[i];
    ans = min(ans, now);
    ans = min(ans, now + (k + 1 > n ? INF : table.query(k + 1, n, true)) - table.query(1, k, false));
    debug(ans);
    for (int i = k + 1; i <= n; ++i) {
        now -= v[i - k] - v[i];
        debug(now, i);
        ans = min(ans, now);
        ans = min(ans, now + min(table.query(1, i - k, true), (i == n ? INF : table.query(i + 1, n, true))) - table.query(i - k + 1, i, false));
    }
    cout << ans << '\n';
}

signed main() {
    cin.tie(0)->sync_with_stdio(0);
    int t = 1;
    cin >> t;
    for (int _ = 1; _ <= t; ++_) {
        // cout << "Case " << _ << ": ";
        shelby();
    }
}

Information

Submit By
Type
Submission
Problem
P1149 Swap and Minimize
Language
C++17 (G++ 13.2.0)
Submit At
2025-01-26 10:14:31
Judged At
2025-01-26 10:14:31
Judged By
Score
100
Total Time
62ms
Peak Memory
25.566 MiB