DP(10)

Bicolored Horses

Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Description

Every day, farmer Ion (this is a Romanian name) takes out all his horses, so they may run and play. When they are done, farmer Ion has to take all the horses back to the stables. In order to do this, he places them in a straight line and they follow him to the stables. Because they are very tired, farmer Ion decides that he doesn't want to make the horses move more than they should. So he develops this algorithm: he places the 1st P 1 horses in the first stable, the next P 2 in the 2nd stable and so on. Moreover, he doesn't want any of the K stables he owns to be empty, and no horse must be left outside. Now you should know that farmer Ion only has black or white horses, which don't really get along too well. If there are black horses and j white horses in one stable, then the coefficient of unhappiness of that stable isi*j. The total coefficient of unhappiness is the sum of the coefficients of unhappiness of every of the K stables.
Determine a way to place the N horses into the K stables, so that the total coefficient of unhappiness is minimized.

Input

On the 1st line there are 2 numbers: N (1 ≤ N ≤ 500) and K (1 ≤ K ≤ N). On the next N lines there are N numbers. The i-th of these lines contains the color of the i-th horse in the sequence: 1 means that the horse is black, 0 means that the horse is white.

Output

You should only output a single number, which is the minimum possible value for the total coefficient of unhappiness.

Sample Input

inputoutput
6 3
1
1
0
1
0
1
2

Notes

Place the first 2 horses in the first stable, the next 3 horses in the 2nd stable and the last horse in the 3rd stable. 
 
最优子结构:部分最优符合全局最优。
 
 
#include<cstdio>
#include<algorithm>
const int INF = 0x3f3f3f3f;
const int maxn = 505;
using namespace std;
int num0[maxn];
int num1[maxn];
int dp[maxn][maxn];
int main(){
    int n,m,x;
    while(~scanf("%d%d",&n,&m)){
        for(int i = 1; i <= n; i++){
            scanf("%d",&x);
            num1[i] = num1[i-1] + x;//1,0的特点!
            num0[i] = num0[i-1] + 1 - x;//1,0的特点!
        }
        for(int i = 0; i <= m; i++)
            for(int j = 0; j <= n; j++)
            dp[i][j] = INF;
        dp[0][0] = 0;
        for(int i = 1; i <= m; i++)
            for(int j = 0; j <= n; j++){//枚举区间;
                for(int k = 0; k <= j; k++)//在区间内dp寻找最优;(枚举0~j,划分出去一段放入下一个马槽)。
                    dp[i][j] = min(dp[i][j],dp[i-1][k]+(num0[j]-num0[k])*(num1[j]-num1[k]));
            }
        printf("%d\n",dp[m][n]);
    }
    return 0;
}

 

posted @ 2015-08-31 19:46  Tobu  阅读(106)  评论(0)    收藏  举报