/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 2ms 332.0 KiB
#2 Accepted 15ms 540.0 KiB
#3 Accepted 24ms 540.0 KiB
#4 Accepted 21ms 540.0 KiB
#5 Accepted 22ms 796.0 KiB
#6 Accepted 35ms 4.07 MiB
#7 Accepted 55ms 18.109 MiB
#8 Accepted 83ms 18.129 MiB
#9 Accepted 82ms 18.141 MiB
#10 Accepted 55ms 18.105 MiB
#11 Accepted 55ms 18.355 MiB
#12 Accepted 54ms 18.301 MiB

Code

#include <bits/stdc++.h>
using namespace std;
#define int long long
#define enl "\n"
#define all(x) x.begin(), x.end()
#define FAST ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
const int N = 2e5 + 19;
const int LOG = 20;

void solve() {
    int n, k;
    cin >> n >> k;

    vector <int> a(n), mn1(n, 1e9), mn2(n, 1e9);
    for(int &i : a) cin >> i;

    mn1[0] = a[0];
    for(int i = 1; i < n; i++) mn1[i] = min(a[i], mn1[i - 1]);

    mn2[n - 1] = a[n - 1]; 
    for(int i = n - 2; i >= 0; i--) mn2[i] = min(a[i], mn2[i + 1]);

    int m[n][LOG];
    for(int i = 0; i < n; i++) {
        m[i][0] = a[i];
    }
    for(int i = 1; i < LOG; i++){
        for(int j = 0; j + (1 << i) - 1 < n; j++){
            m[j][i] = max(m[j][i - 1], m[j + (1 << (i - 1))][i - 1]);
        }
    }


    int sum = 0;
    for(int i = 0; i < k; i++) {
        sum += a[i];
    }

    int l = 31 - __builtin_clz(k);
    int m1 = max(m[0][l], m[k - (1 << l)][l]);
    int ans = sum - m1 + (k == n ? m1 : mn2[k]);
    //cout << (k == n ? 0 : mn2[k]) << enl;

    for(int i = k; i < n; i++) {
        sum = sum - a[i - k] + a[i];
        //min(m[l][k],m[r-(1<<k)+1][k]) 
        int mm = max(m[i - k + 1][l], m[i - (1 << l) + 1][l]);
        int temp = sum - mm + min(mn1[i - k], (i + 1 == n ? (int) 1e9 : mn2[i + 1]));
        ans = min({ans, temp, sum});

        //cout << i << ' ' << sum << ' ' << temp << ' ' << mm << ' ' << mn1[i - k] << ' ' << (i + 1 == n ? (int) 1e9 : mn2[i + 1]) <<  enl;
    }

    cout << ans << enl;
}

signed main()
{
    FAST
    
    int T = 1;
    cin >> T;
    for(int tt = 1; tt <= T; tt++) {
        //cout << "Case " << tt << ": ";
        solve();
    }
    return 0;
    
}

Information

Submit By
Type
Submission
Problem
P1149 Swap and Minimize
Contest
LU IUJPC : Sylhet Division 2024 Replay Contest
Language
C++17 (G++ 13.2.0)
Submit At
2024-12-10 13:02:22
Judged At
2024-12-10 13:02:22
Judged By
Score
100
Total Time
83ms
Peak Memory
18.355 MiB