【动态规划】[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≤ ri ≤1,000,0001≤ ri ≤1,000,000). To herd the cows into the barn in an orderly fashion, he plans to unlock k exterior doors (1≤k≤7), allowing the cows to enter through only those doors. Each cow then walks clockwise through the rooms until she reaches a suitable destination. Farmer John wants to unlock the exterior doors that will cause his cows to collectively walk a minimum total amount of distance after entering the barn (they can initially line up however they like outside the k unlocked doors; this does not contribute to the total distance in question). Please determine the minimum total distance his cows will need to walk, if he chooses the best k such doors to unlock.

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

题目分析

我们令 dp(i,j,k) 表示第一个位置在 i 当前放置的位置在 j 正在选择了第 k 个门的位置的最优状态那么我们显然有答案为 min{dp(i,j,K)} 同时有

dp(i,j,k)=min{dp(i1,t,k1)+val(t,j1,0)}
其中 val(i,j,k) 表示从 i j 中所有的牛从 i 出发归位需要走过的总距离 k 表示修正值为了特殊处理当 k=K 的情况
dp(i,j,K)=min{dp(i,t,k1)+val(t,j1,0)+val(j,n,0)+val(1,i,nj+1)}

代码

#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;
}

你可能感兴趣的:(算法,动态规划,USACO,信息竞赛,金组)