sgu 183. Painting the balls 动态规划 难度:3

183. Painting the balls

time limit per test: 0.25 sec.
memory limit per test: 4096 KB
input: standard input
output: standard output




Petya puts the N white balls in a line and now he wants to paint some of them in black, so that at least two black balls could be found among any M successive balls. Petya knows that he needs Ci milliliters of dye exactly to paint the i-th ball. Your task is to find out for Petya the minimum amount of dye he will need to paint the balls.

Input
The first line contains two integer numbers N and M (2<=N<=10000, 2<=M<=100, M<=N). The second line contains N integer numbers C1, C2, ..., CN (1<=Ci<=10000).

Output
Output only one integer number - the minimum amount of dye Petya will need (in milliliters).

Sample test(s)

Input
 
 
6 3 
1 5 6 2 1 3
 
 

Output
 
 
9
 
 

Note
Example note: 1, 2, 4, 5 balls must be painted.

思路:dp[i][j]//在i染色,在i-j染色的最小花费 设a b更新到,a b c,由远(距a m-1距c 1)到近以b为中心更新dp即可

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=10001;
const int maxm=101;
const int inf=1e9+5;
int dp[maxn][maxm];//back maxm
int c[maxn];
int n,m;
int main(){
    while(scanf("%d%d",&n,&m)==2){
        //memset(dp,0,sizeof(dp));
        for(int i=0;i<n;i++)scanf("%d",c+i);
        for(int i=0;i<m;i++){
            for(int j=0;j<i;j++){
                dp[i][i-j]=c[i]+c[j];//g[i-j]=min(dp[i][j],g[i-j]);
            }
        }
        for(int j=1;j<n;j++){
            int minn=inf;
            for(int i=min(n,j+m)-1;i>j&&i>=m;i--){
                minn=min(dp[j][m+j-i],minn);
                dp[i][i-j]=minn+c[i];
            }
        }
        int ans=inf;
        for(int i=n-m+1;i<n;i++){
                for(int j=min(m-1,i-n+m);j>0;j--)
            ans=min(ans,dp[i][j]);
        }
        printf("%d\n",ans);
    }
    return 0;
}

  

 
原文地址:https://www.cnblogs.com/xuesu/p/3978294.html