URAL 1167. Bicolored Horses(DP)

题目链接

二维DP,开两个标记数组记录前i个数1的个数,和0的个数。1Y。

状态转移方程:p[i][j] = min(p[i-k][j-1]+(sum1(i)-sum1(i-k))*(sum0(i)-sum0(i-k))(开始的时候i-k想成k了。。自己试了几个数据没过,手算查错)

 1 #include <stdio.h>

 2 #include <string.h>

 3 #define N 10000000

 4 int p[501][501],sum1[501],sum0[501];

 5 int main()

 6 {

 7     int n,m,i,j,k;

 8     scanf("%d%d",&n,&m);

 9     for(i = 1;i <= n;i ++)

10     {

11         scanf("%d",&j);

12         if(j == 1)

13         {

14             sum1[i] = sum1[i-1]+1;

15             sum0[i] = sum0[i-1];

16         }

17         else

18         {

19             sum0[i] = sum0[i-1]+1;

20             sum1[i] = sum1[i-1];

21         }

22     }

23     for(i = 1;i <= n;i ++)

24     {

25         for(j = 1;j <= m;j ++)

26         p[i][j] = N;

27     }

28     for(i = 1;i <= n;i ++)

29     {

30         p[i][1] = sum1[i]*sum0[i];

31     }

32     for(i = 1;i <= n;i ++)

33     {

34         for(j = 2;j <= m&&j <= i;j ++)

35         {

36             for(k = 1;k <= i&&i-k>=j-1;k ++)

37             {

38                if(p[i][j] > p[i-k][j-1]+(sum1[i]-sum1[i-k])*(sum0[i]-sum0[i-k]))

39                p[i][j] =  p[i-k][j-1]+(sum1[i]-sum1[i-k])*(sum0[i]-sum0[i-k]);

40             }

41         }

42     }

43     printf("%d\n",p[n][m]);

44     return 0;

45 }

你可能感兴趣的:(color)