您的位置:首页 > 大数据 > 人工智能

SGU 183 Painting the balls (DP优化)

2014-08-18 18:00 483 查看


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.

题意:给一些白球排成一排,将其中的一些球染黑,对应的需要付出相应的代价,要求染黑后每M个球中至少有两个黑球。求最小需要付出的代价;

分析:这题很容易想到一个状态方程,dp[i][j] = c[j] + min{dp[k][i]} i,j分别表示最后两个球的位置。如果直接做,复杂度是O(N*M*M),会超时。而且N*N的空间也无法承受。在空间上,我们可以使用滚动数组进行优化,节省空间。在时间上,我们注意到,对于相同的i,如果对j由大到小枚举,会有重叠的部分,可以直接以O(1)的复杂度得到min{dp[k][i]},从而把复杂度降到了O(M*N)

AC代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 10005;
const int M =  110;
const int INF = 0x3f3f3f3f;
int n,m;
int c
,dp[M+10][M+10];
int main()
{
while(scanf("%d%d",&n,&m)==2){
for(int i=0;i<n;i++)scanf("%d",&c[i]);
int ret = INF;
memset(dp,0x3f,sizeof(dp));
for(int i=0;i<m;i++)
for(int j=i+1;j<m;j++)
dp[i][j] = c[i]+c[j];
for(int i=0;i<n;i++){
int minn = INF;
//printf("fff:%d %d\n",minn,minx);
for(int j=min(i+m-1,n-1);j>max(i,m-1);j--){
if(minn>dp[(j-m)%M][i%M])minn = dp[(j-m)%M][i%M];
//printf("fff:%d %d\n",minn,minx);
dp[i%M][j%M] = c[j] + minn;
//cout<<dp[i%M][j%M]<<endl;
}
}
for(int i=n-1; i>=n-m; i--)
for(int j=i-1; i-j<m&&j>=n-m; j--)
ret=min(ret,dp[j%M][i%M]);
cout<<ret<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: