题意:有n个饭店,要在n个饭店中选k个建立补给站给距离最近的饭店补给,给出n个饭店的位置,问补给站建在哪k个饭店并且将饭店和自己的补给站的距离和输出。
题解:f[i][j]代表在前j个饭店建i个补给站的距离和。先用一个dis[i][j]表示从i到j建立1个补给站的总距离(一定是(i + j) / 2这个距离其他几个点距离和最小),那么状态转移方程就是f[i][j] = min{f[i][j],f[i - 1][k] + dis[k + 1][j]}。最后根据f数组递归打印路径。
#include <stdio.h>
#include <string.h>
#include <math.h>
const int N = 205;
const int INF = 0x3f3f3f3f;
int n, k, p[N];
int f[N][N], dis[N][N];
void print_path(int r, int k) {
if (k == 1) {
if (r == 1)
printf("Depot 1 at restaurant 1 serves restaurant 1\n");
else
printf("Depot 1 at restaurant %d serves restaurants 1 to %d\n", (1 + r) / 2, r);
return;
}
for (int i = r - 1; i >= 1; i--) {
if (f[k][r] == f[k - 1][i] + dis[i + 1][r]) {
print_path(i, k - 1);
if (i + 1 == r)
printf("Depot %d at restaurant %d serves restaurant %d\n", k, r, r);
else
printf("Depot %d at restaurant %d serves restaurants %d to %d\n", k, (i + 1 + r) / 2, i + 1, r);
break;
}
}
}
int main() {
int cas = 1;
while (scanf("%d%d", &n, &k) && (n + k)) {
memset(f, INF, sizeof(f));
for (int i = 1; i <= n; i++)
scanf("%d", &p[i]);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
dis[j][i] = 0;
int mid = p[(j + i) / 2];
for (int k = j; k <= i; k++) {
dis[j][i] += fabs(p[k] - mid);
}
}
}
for (int i = 1; i <= n; i++)
f[1][i] = dis[1][i];
for (int i = 2; i <= k; i++) {
for (int j = i; j <= n; j++) {
for (int k = i - 1; k <= j; k++) {
f[i][j] = f[i][j] < f[i - 1][k] + dis[k + 1][j] ? f[i][j] : f[i - 1][k] + dis[k + 1][j];
}
}
}
printf("Chain %d\n", cas++);
print_path(n, k);
printf("Total distance sum = %d\n\n", f[k][n]);
}
return 0;
}