Bicolored horses
N horses and K stables for you. Each horse will only be 0 or 1, there will be an unhappy value in each horse store (the unhappy value = the number of 0 horses * The number of 1 horses). How can we obtain a minimum unhappy value, output the smallest unhappy value.
Idea: First (N ^ 2) process the unhappy values in each interval, and then use DP to obtain the minimum unhappy values of K stables.
DP [I] [J], I indicates the number of stables currently allocated, and J indicates the number of horses currently allocated.
1 /************************************** * *********************************** 2> File Name: ural1167.cpp 3> author: glsilence 4> created time: ******************************* **************************************** */6 7 # include <stdio. h> 8 # include <iostream> 9 Using namespace STD; 10 const int INF = 0x7ffffff; 11 12 int a [505]; 13 int B [505] [505], c [505] [505]; 14 int sum [505] [505]; 15 int DP [505] [505]; 16 17 int main () 18 {19 int N, k; 20 scanf ("% d", & N, & K); 21 for (INT I = 1; I <= N; ++ I) {22 scanf ("% d", & A [I]); 23 DP [0] [I] = inf; 24} 25 26 for (INT I = 1; I <= N; ++ I) {27 for (Int J = I; j <= N; ++ J) {28 if (a [J] = 0) {29 B [I] [J] = B [I] [J-1] + 1, C [I] [J] = C [I] [J-1]; 30} 31 else {32 B [I] [J] = B [I] [J-1], C [I] [J] = C [I] [J-1] + 1; 33} 34 35 sum [I] [J] = B [I] [J] * C [I] [J]; 36} 37} 38 int P; 39 For (INT I = 1; I <= K; ++ I) {40 for (Int J = 1; j <= N; ++ J) {41 int min = inf; 42 for (int t = 1; t <= J; ++ T) {43 p = DP [I-1] [T-1] + sum [T] [J]; 44 min = min (min, P ); 45} 46 DP [I] [J] = min; 47} 48} 49 printf ("% d \ n", DP [k] [N]); 50 51 return 0; 52}
URL 1167