/ SeriousOJ /

Record Detail

Time Exceeded


  
# Status Time Cost Memory Cost
#1 Accepted 2ms 540.0 KiB
#2 Accepted 54ms 824.0 KiB
#3 Accepted 99ms 588.0 KiB
#4 Time Exceeded ≥2099ms ≥544.0 KiB
#5 Time Exceeded ≥2097ms ≥540.0 KiB

Code

#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
using namespace std;

// Function to calculate the minimum sum of a subarray of length K
int findMinSumWithSwap(int N, int K, vector<int>& A) {
    // Compute initial minimum sum using a sliding window
    int currentSum = 0, minSum = INT_MAX;
    for (int i = 0; i < K; ++i)
        currentSum += A[i];
    minSum = currentSum;

    for (int i = K; i < N; ++i) {
        currentSum += A[i] - A[i - K];
        minSum = min(minSum, currentSum);
    }

    // Try swapping every pair of elements
    for (int i = 0; i < N; ++i) {
        for (int j = i + 1; j < N; ++j) {
            // Swap elements A[i] and A[j]
            swap(A[i], A[j]);

            // Recompute the sliding window minimum sum
            currentSum = 0;
            for (int k = 0; k < K; ++k)
                currentSum += A[k];
            int swappedMinSum = currentSum;

            for (int k = K; k < N; ++k) {
                currentSum += A[k] - A[k - K];
                swappedMinSum = min(swappedMinSum, currentSum);
            }

            // Update the overall minimum sum
            minSum = min(minSum, swappedMinSum);

            // Swap back to restore the original array
            swap(A[i], A[j]);
        }
    }

    return minSum;
}

int main() {
    int T;
    cin >> T;
    while (T--) {
        int N, K;
        cin >> N >> K;
        vector<int> A(N);
        for (int i = 0; i < N; ++i)
            cin >> A[i];
        cout << findMinSumWithSwap(N, K, A) << endl;
    }
    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 12:34:04
Judged At
2024-12-10 12:34:04
Judged By
Score
20
Total Time
≥2099ms
Peak Memory
≥824.0 KiB