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; }
相关文章推荐
- sgu183:Painting the balls(dp+优化)
- SGU183 Painting the balls(DP+优化)
- sgu183 Painting the balls_dp
- SGU 183 Painting the balls(DP)
- Painting the balls SGU - 183
- HDU 3698 Let the light guide us 线段树求区间优化dp
- SGU 407-Number of Paths in the Empire【DP】
- poj 3017 Cut the Sequence dp+单调队列优化
- HDU2227 - Find the nondecreasing subsequences(线段树优化DP)
- dp优化专辑 I - Cut the Tree [树形dp]
- Poj 3017 Cut the Sequence (DP,单调队列优化,数据结构优化)
- POJ 3017 Cut the Sequence (单调队列优化DP)
- poj 3017 Cut the Sequence(dp单调队列优化)
- hdu 3698 Let the light guide us(线段树优化&简单DP)
- CF 319C - Kalila and Dimna in the Logging Industry 斜率优化DP
- Light OJ 1317 Throwing Balls into the Baskets 概率DP
- SGU 365 Ships of the Desert 简单数位dp
- POJ--3017--Cut the Sequence--DP优化
- poj3017 Cut the Sequence 单调队列优化dp 好题!
- sgu148:B-Station(dp+堆优化)