Pagini recente » Cod sursa (job #3298491) | Cod sursa (job #3298796) | Cod sursa (job #3298663) | Cod sursa (job #3280956) | Cod sursa (job #3298797)
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int weight; int value;
} Item;
Item* read_items(FILE *f, int items) {
Item *items_array = malloc(items * sizeof(Item));
if (items_array == NULL) {
printf("Error: not enough memory\n");
exit(1);
}
for (int i = 0; i < items; i++) {
fscanf(f, "%d %d", &items_array[i].weight, &items_array[i].value);
}
return items_array;
}
int compare(const void *a, const void *b) {
Item *itemA = (Item *) a;
Item *itemB = (Item *) b;
double ratioA = (double) itemA->value / itemA->weight;
double ratioB = (double) itemB->value / itemB->weight;
return (ratioA < ratioB) - (ratioA > ratioB);
}
void sort_items(Item *items_array, int items) {
qsort(items_array, items, sizeof(Item), compare);
}
void print_items(Item *items_array, int items) {
for (int i = 0; i < items; i++) {
printf("%d %d %lf\n", items_array[i].weight, items_array[i].value, (double) items_array[i].value / items_array[i].weight);
}
}
int pick_items(Item *items_array, int item_count, int max_weight) {
int weight = 0, total_value = 0, idx = 0;
while (weight < max_weight && idx < item_count ) {
if (weight + items_array[idx].weight <= max_weight) {
weight += items_array[idx].weight;
total_value += items_array[idx].value;
idx++;
} else {
idx++;
}
}
return total_value;
}
int main() {
FILE *f = fopen("rucsac.in", "r");
f == NULL && printf("Error: file not found\n");
FILE *o = fopen("rucsac.out", "w");
f == NULL && printf("Error: file not found\n");
int item_count = 0, max_weight = 0;
fscanf(f, "%d %d", &item_count, &max_weight);
Item *items_array = read_items(f, item_count);
sort_items(items_array, item_count);
int max_value = pick_items(items_array, item_count, max_weight);
fprintf(o, "%d", max_value);
return 0;
}