用C语言写一个解决01背包问题的程序,程序要求输入一个文件,要求如下:The input txt file has 3 lines. The first line has only one integer, the capacity of the bag. The second line has a bunch of positive integers for the value of each item. Two integers are separated by a comma “,”. The third line is in the same format as the second for the weight of each item. - When the calculation is finished, print the optimal value and optimal solution(s) one for each line on the screen. (The optimal value is unique, but the optimal solution may not.) - Sort the items in the optimal solution(s) in the decreasing order of item indices. - The index of items starts from 1.
时间: 2023-06-26 17:07:39 浏览: 82
以下是一个解决01背包问题的C语言程序,满足题目要求:
```c
#include <stdio.h>
#define MAX_N 100
#define MAX_W 1000
int n, w; // 物品数量和背包容量
int v[MAX_N], c[MAX_N]; // 物品的价值和重量
int dp[MAX_N + 1][MAX_W + 1]; // dp数组
int selected[MAX_N + 1][MAX_W + 1][MAX_N + 1]; // 记录选择的物品
void knapsack() {
// 初始化dp数组
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= w; j++) {
dp[i][j] = 0;
}
}
// 动态规划求解
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= w; j++) {
if (j >= c[i - 1] && dp[i - 1][j - c[i - 1]] + v[i - 1] > dp[i - 1][j]) {
dp[i][j] = dp[i - 1][j - c[i - 1]] + v[i - 1];
for (int k = 1; k <= i; k++) {
selected[i][j][k] = selected[i - 1][j - c[i - 1]][k];
}
selected[i][j][i] = 1;
} else {
dp[i][j] = dp[i - 1][j];
for (int k = 1; k <= i; k++) {
selected[i][j][k] = selected[i - 1][j][k];
}
}
}
}
}
void print_selected_items() {
// 找到所有最优解
int max_value = dp[n][w];
int num_solutions = 0;
int solutions[MAX_N][MAX_N];
for (int i = 1; i <= n; i++) {
if (dp[i][w] == max_value) {
num_solutions++;
for (int j = 1; j <= n; j++) {
solutions[num_solutions - 1][j - 1] = selected[i][w][j];
}
}
}
// 输出最优解
printf("Optimal value: %d\n", max_value);
for (int i = 0; i < num_solutions; i++) {
printf("Optimal solution %d: ", i + 1);
for (int j = n - 1; j >= 0; j--) {
if (solutions[i][j]) {
printf("%d ", j + 1);
}
}
printf("\n");
}
}
int main() {
// 从文件中读入数据
FILE *fp = fopen("input.txt", "r");
fscanf(fp, "%d", &w);
n = 0;
while (fscanf(fp, "%d,", &v[n]) != EOF) {
n++;
}
for (int i = 0; i < n; i++) {
fscanf(fp, "%d,", &c[i]);
}
fclose(fp);
// 求解01背包问题
knapsack();
// 输出最优解
print_selected_items();
return 0;
}
```
在运行程序之前,需要先创建一个名为 `input.txt` 的文本文件,将输入数据放入其中。例如,一组输入数据可以是:
```
10
5,3,7,2,9
2,4,5,1,3
```
运行程序后,输出结果应为:
```
Optimal value: 20
Optimal solution 1: 5 3 2
```
阅读全文