Skip to content

USACO 2016 February Contest Gold Division - Circular Barn Revisited#

Problem link: here

Solution Author: Stefan Dascalescu

Problem Solution#

This problem can be done using DP as we rely on the small constraints and the few places we open in order to run a 2D DP solution.

Source code#

The source code in C++ can be seen below.

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

void solve() {
    ifstream fin("cbarn2.in");
    int n, open;
    fin >> n >> open;
    vector<int> vals(n);
    for (int i = 0; i < n; i++)
        fin >> vals[i];
    fin.close();

    long long res = 100000000000LL;

    for (int start = 0; start < n; start++) {
        vector<int> arr(n);
        for (int i = start; i < start + n; i++) {
            arr[i - start] = vals[i % n];
        }

        vector<vector<long long>> dp(open, vector<long long>(n, 0));
        for (int i = 1; i < n; i++) {
            dp[0][i] = dp[0][i - 1] + 1LL * i * arr[i];
        }

        for (int i = 1; i < open; i++) {
            for (int j = i + 1; j < n; j++) {
                dp[i][j] = dp[i - 1][j];
                int sum = 0, people = arr[j];
                int k = j - 1;
                while (k > 0 && sum < dp[i][j]) {
                    sum += people;
                    dp[i][j] = min(dp[i][j], dp[i - 1][k - 1] + sum);
                    people += arr[k];
                    k--;
                }
            }
        }

        res = min(res, dp[open - 1][n - 1]);
    }

    ofstream fout("cbarn2.out");
    fout << res << "\n";
    fout.close();
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t = 1;
    while (t--) {
        solve();
    }
    return 0;
}