#include <stdio.h>
#include <stdlib.h>
int* optimizeTravel(int* time, int* score, int days, int n) {
int** dp = (int**)malloc((n+1) * sizeof(int*));
for (int i = 0; i <= n; i++) {
dp[i] = (int*)malloc((days+1) * sizeof(int));
for (int j = 0; j <= days; j++) {
dp[i][j] = 0;
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= days; j++) {
if (j >= time[i-1]) {
dp[i][j] = (dp[i-1][j] > dp[i-1][j-time[i-1]] + score[i-1]) ? dp[i-1][j] : dp[i-1][j-time[i-1]] + score[i-1];
} else {
dp[i][j] = dp[i-1][j];
}
}
}
// 找出能够获得最大价值的景点
int* selected_spots = (int*)malloc(n * sizeof(int));
int j = days;
int count = 0;
for (int i = n; i > 0; i--) {
if (dp[i][j] > dp[i-1][j]) {
selected_spots[count] = i;
j -= time[i-1];
count++;
}
}
// 释放动态分配的内存
for (int i = 0; i <= n; i++) {
free(dp[i]);
}
free(dp);
return selected_spots;
}
int main() {
char* spots[] = {"故宫", "颐和园", "长城", "天坛"};
int time[] = {1, 2, 3, 1};
int score[] = {7, 8, 9, 6};
int days = 4;
int n = sizeof(time) / sizeof(time[0]);
int* selected_spots = optimizeTravel(time, score, days, n);
printf("去哪些景点能够获得最大价值:\n");
for (int i = 0; i < n; i++) {
printf("%s\n", spots[selected_spots[i]-1]);
}
free(selected_spots);
return 0;
}