【动态规划】[USACO2016 金组]Circular Barn Revisited
题目描述
After the last debacle involving Farmer John’s circular barn, one would think he had learned his lesson about non-traditional architecture. However, he thinks he can still make his circular barn (from the preceding problem) function properly by allowing multiple cows into each room. To recap, the barn consists of a ring of nn rooms, numbered clockwise from 1…n1…n around the perimeter of the barn (3≤n≤1003≤n≤100). Each room has doors to its two neighboring rooms, and also a door opening to the exterior of the barn.
Farmer John wants exactly riri cows to end up in room ii (1≤
INPUT FORMAT (file cbarn2.in):
The first line of input contains nn and kk. Each of the remaining nn lines contain r1…rnr1…rn.
OUTPUT FORMAT (file cbarn2.out):
Please write out the minimum amount of distance the cows need to travel.
SAMPLE INPUT:
6 2
2
5
4
2
6
2
SAMPLE OUTPUT:
14
题目分析
我们令
代码
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 100;
const long long INF = 1e18+7;
long long dp[MAXN+10][10], sum[MAXN+10];
int n, k;
inline long long val(int l, int r, long long fix){
long long ret = 0;
for(int i=l;i<r;i++)
ret += sum[i] * (i - l + fix);
return ret;
}
long long solve(int beg){
for(int i=1;i<k;i++){
for(int j=1;j<=n;j++) if(~dp[j][i]){
for(int t=j+1;t<=n;t++){
if(dp[t][i+1] == -1) dp[t][i+1] = INF;
dp[t][i+1] = min(dp[t][i+1], dp[j][i]+val(j, t, 0));
}
}
}
long long ret = INF;
for(int i=1;i<=n;i++)
if(~dp[i][k])
ret = min(ret, dp[i][k]+val(i, n+1, 0)+val(1, beg, n-i+1));
return ret;
}
int main(){
scanf("%d%d", &n, &k);
for(int i=1;i<=n;i++)scanf("%lld", &sum[i]);
long long ans = INF;
for(int i=1;i<=n;i++){
memset(dp, -1, sizeof dp);
dp[i][1] = 0;
ans = min(ans, solve(i));
}
printf("%lld\n", ans);
return 0;
}