URAL -1167 Bicolored Horses

来源:互联网 发布:淘宝网一元秒杀好抢吗 编辑:程序博客网 时间:2024/05/16 19:51

 

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 P2 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 is i*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.
Example
inputoutput
6 3110101
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.



     题意是:

有n只马,这n只马有白色(用0表示)和黑色(用1表示)两种。当一个马栏里面存在不同种类的马时,会有一个不开心值为白马的数量*黑马的数量,现在要求的是把这些马分配到马兰里(马栏必须有马),求怎样分才会使得这个不开心值最小
     
     思路:

1.首先,我们要枚举区间的不开心值,我们用num[i][j]表示在给出的n只马中从第i只到第j只马的不开心值

2.接下来就是转化为dp,用dp[i][j]表示在前i个马栏的分配前j只马所得到的最小不开心值,状态转移方程dp[i][j]=min(dp[i][j],dp[i-1][k-1]+num[k][j])

num[k][j]为枚举前j只马的不开心值,取最小然后保存状态。


#include <iostream>#include <stdio.h>#include <cstring>#include <algorithm>#include <cmath>#include <queue>#define mst(a,b) memset(a,b,sizeof(a))const int inf=0x3f3f3f3f;const int maxn=1000005;using namespace std;int a[505],num[505][505],dp[505][505];int main(){    int N,K;    scanf("%d%d",&N,&K);    for(int i=1;i<=N;i++){        scanf("%d",&a[i]);    }    for(int i=1;i<=N;i++){            int w=0,b=0;        for(int j=i;j<=N;j++){            if(a[j]) b++;            else w++;            num[i][j]=b*w;        }    }    for(int i=1;i<=N;i++){        dp[0][i]=inf;    }    for(int i=1;i<=K;i++){        for(int j=1;j<=N;j++){            dp[i][j]=inf;            for(int k=1;k<=j;k++){                dp[i][j]=min(dp[i][j],dp[i-1][k-1]+num[k][j]);            }        }    }    printf("%d\n",dp[K][N]);    return 0;}


原创粉丝点击