1 // accepted 420 KB 15 MS 2 // At the beginning I was trying to put depot in which restaurant, and the result was stuck in it, I don't know how to transfer it. 3 // now we treat I to J as a piece of processing, and we think that I to J is supplied by a depot, but it has nothing to do with other depots, and 4 // This depot has nothing to do with other restaurants, then the cost of the I to J segment can be calculated 5 // expressed by cost [I] [J]. For the I to J segment, put the depot on the restaurant (I + J)/2, the resulting cost is at least 6 // The following is DP. 7 // DP [I] [J] indicates the minimum cost of placing J depots in the first one. 8 // DP [I] [J] = min (DP [m] [J-1] + cost [M + 1] [I]) j-1 <= m <= I-1 9 // now it's time to see no postfix in dynamic planning .... 10 # include <cstdio> 11 # include <cstring> 12 # include <iostream> 13 using namespace STD; 14 const int imax_n = 201; 15 const int imax_k = 31; 16 const int INF = 100000000; 17 int N, K; 18 int cost [imax_n] [imax_n]; 19 int DP [imax_n] [imax_k]; 20 int dis [imax_n]; 21 22 int ABS (int x) 23 {24 if (x <0) x =-X; 25 return X; 26} 27 int min (int A, int B) 28 {29 return A> B? B: A; 30} 31 void getcost () 32 {33 for (INT I = 1; I <= N; I ++) 34 {35 for (Int J = I; j <= N; j ++) 36 {37 cost [I] [J] = 0; 38 int temp_mid = (I + J)/2; 39 For (int K = I; k <= J; k ++) 40 cost [I] [J] + = ABS (DIS [temp_mid]-Dis [k]); 41} 42} 43} 44 void dp () 45 {46 for (INT I = 0; I <= N; I ++) 47 for (Int J = 0; j <= K; j ++) 48 DP [I] [J] = inf; 49 DP [0] [0] = 0; 50 for (INT I = 1; I <= N; I ++) 51 {52 for (Int J = 1; j <= K & J <= I; j ++) 53 {54 for (int m = J-1; m <= I-1; m ++) 55 DP [I] [J] = min (DP [I] [J], DP [m] [J-1] + cost [M + 1] [I]); 56} 57} 58} 59 int main () 60 {61 int T = 0; 62 while (scanf ("% d", & N, & K), N + k) 63 {64 for (INT I = 1; I <= N; I ++) 65 scanf ("% d", & dis [I]); 66 getcost (); 67 dp (); 68 printf ("chain % d \ n ", + + T); 69 printf ("total distance sum = % d \ n", DP [N] [k]); 70} 71 return 0; 72}
View code