USACO Gold 2016 February - Circular Barn Revisited
Author: Chuyang Wang
Explanation
The problem asks for the minimum amount of distance the cows need to travel for a circular barn. However, if we fix the position of the first door, the problem can be reduced to a linear barn where we place the first door at the beginning of our linear barn. In such case, we can define as the sum of distance to fill the rooms if we place the -th door at . All values of the array are initialized with infinity. We further set because with no doors the only case where the distance is zero is to fill no room. Our transitions would then be
,
where and . In other words, is the minimum of all distances if we put the -th door at with the last door placed at some place after . This distance is calculated by adding the distance to fill the rooms to the optimal amount of distance to fill rooms with doors. represents the minimum amount of distance needed if we place the first door at the beginning of the current array . We then start from the second door by moving the first room to the end of the array and do the DP again.
Our answer would be the minimum distance among all possible positions for the first door.
There are doors which can be chosen as the first door. In each DP, we add each time one of the doors and iterate through each of positions to place it. For each of these positions, we go through all possible placement of the last door and calculate the optimal result for our current position with the new door. This yields a total time complexity of , which is fast enough for the given constraints.
Implementation
C++
#include <bits/stdc++.h>using namespace std;int main() {freopen("cbarn2.in", "r", stdin);freopen("cbarn2.out", "w", stdout);int n, k;cin >> n >> k;deque<int> rooms(n);
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!