给出C语言贪心算法解决背包问题的最佳答案
时间: 2023-06-08 09:04:41 浏览: 101
贪心算法求解背包问题
4星 · 用户满意度95%
C语言贪心算法解决背包问题的最佳答案如下:
```c
#include <stdio.h>
#define MAX_N 100
struct Item {
int weight, value;
};
int cmp(const void *a, const void *b) {
const struct Item *x = a;
const struct Item *y = b;
double ratio_a = (double)x->value / x->weight;
double ratio_b = (double)y->value / y->weight;
if (ratio_a < ratio_b) return +1;
if (ratio_a > ratio_b) return -1;
return 0;
}
int main() {
int n, w;
struct Item items[MAX_N];
while (scanf("%d %d", &n, &w) == 2) {
for (int i = 0; i < n; i++) {
scanf("%d %d", &items[i].weight, &items[i].value);
}
qsort(items, n, sizeof(*items), cmp);
int ans = 0;
for (int i = 0; i < n && w > 0; i++) {
int t = w < items[i].weight ? w : items[i].weight;
ans += t * items[i].value / items[i].weight;
w -= t;
}
printf("%d\n", ans);
}
return 0;
}
```
阅读全文