1 #include<iostream> 2 using namespace std; 3 4 5 int i, j, m; 6 int *d;//沿高速公路n个快餐店的位置 7 int n, k;//饭店的数量,仓库的数量 8 int cost[202][202]; 9 int dis[205][205]; 10 int temp; 11 12 13 void madecost()//计算数组cost[][]:在任意两个饭店中间建一个仓库时,该两个饭店之间的所有饭店与该仓库的距离和 14 { 15 for (i = 1; i <= n; i++) 16 { 17 for (j = 1; j <= n; j++) 18 { 19 temp = (i + j) / 2; 20 cost[i][j] = 0; 21 for (m = i; m <= j; m++) 22 cost[i][j] += abs(d[m] - d[temp]); 23 } 24 } 25 } 26 27 28 void DP()//动态规划 29 { 30 memset(dis, 1, sizeof(dis)); 31 for (i = 1; i <= n; i++) 32 dis[1][i] = cost[1][i]; 33 for(i=2;i<=k;i++) 34 for (j = i; j <= n; j++) 35 for (m = i - 1; m < j; m++) 36 { 37 temp = dis[i - 1][m] + cost[m + 1][j]; 38 if (temp < dis[i][j]) 39 dis[i][j] = temp; 40 } 41 42 } 43 44 45 void main() 46 { 47 cin >> n >> k; 48 d = new int[n+1]; 49 for (int x = 1; x <= n; x++) 50 cin >> d[x]; 51 madecost(); 52 DP(); 53 cout << "Total distance sum=" << dis[k][n] << endl; 54 55 56 }