首页 > 代码库 > URAL 1167. Bicolored Horses dp
URAL 1167. Bicolored Horses dp
点击打开链接
1167. Bicolored Horses
Time limit: 1.0 second
Memory limit: 64 MB
Memory limit: 64 MB
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 P1 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 i 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.
Sample
input | output |
---|---|
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.
Problem Author: Mugurel Ionut Andreica
Problem Source: Romanian Open Contest, December 2001
Problem Source: Romanian Open Contest, December 2001
将n匹马按照顺序放进k个马槽里,每个马槽里面的不愉快值为颜色为0的马和颜色为1的马的乘积,求怎么放才能使得总的不愉快值最小。
首先预处理出每个区间的马的不愉快值,然后求出总的不愉快值。
dp[i][j]代表在前i个马槽,前j匹马最小的不愉快值,状态转移方程:
dp[i][j]=min(dp[i][j],dp[i-1][k-1]+unhappy[k][j]); 当前马槽的前j匹马最小不愉快值=上一个马槽前k匹马最小不愉快值+将k到j匹马放到第i个马槽的不愉快值.
//0.125 2 202 KB #include<stdio.h> #include<string.h> #include<algorithm> #define inf 0x3f3f3f3f using namespace std; int h[507],dp[507][507],unhappy[507][507]; int main() { int n,kk; while(scanf("%d%d",&n,&kk)!=EOF) { for(int i=1;i<=n;i++) scanf("%d",&h[i]); memset(unhappy,0,sizeof(unhappy)); for(int i=1;i<=n;i++)dp[0][i]=inf; int b,w; for(int i=1;i<=n;i++)//预处理每段区间的不愉快值 { b=0;w=0; for(int j=i;j<=n;j++) { if(h[j])b++;else w++; unhappy[i][j]=b*w; } } for(int i=1;i<=kk;i++)//k个马槽 for(int j=1;j<=n;j++)//前j匹马 { dp[i][j]=inf; for(int k=1;k<=j;k++)//枚举前j匹马 dp[i][j]=min(dp[i][j],dp[i-1][k-1]+unhappy[k][j]); } printf("%d\n",dp[kk][n]); } return 0; }
URAL 1167. Bicolored Horses dp
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。