Pagini recente » Cod sursa (job #2743024) | Cod sursa (job #1019996) | Cod sursa (job #2488177) | Cod sursa (job #1602633) | Cod sursa (job #3133705)
#include <stdio.h>
#include <stdlib.h>
#define MAXN 5001
#define MAXG 10001
struct rucsac{
int greutate, profit;
double ratio;
} obiecte[5001], aux;
int w[MAXG], p[MAXN];
int main() {
int n, maxWeight;
int profitMax = 0;
double p = 0;
FILE *f = fopen("rucsac.in.txt", "r");
if (f == NULL) {
printf("Error opening the file!\n");
return 1;
}
if (fscanf(f, "%d %d", &n, &maxWeight) != 2) {
printf("Error reading 1st line\n");
return 1;
}
for (int i = 0; i < n; i++) {
fscanf(f, "%d %d", &obiecte[i].greutate, &obiecte[i].profit);
obiecte[i].ratio = (double)obiecte[i].profit / obiecte[i].greutate;
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (obiecte[i].ratio < obiecte[j].ratio) {
aux = obiecte[i];
obiecte[i] = obiecte[j];
obiecte[j] = aux;
}
}
}
//qsort(obiecte,n,sizeof(obiecte[0]),sortareRatio);
// for (int i=0; i<n; i++)
// printf("%lf\n",obiecte[i].ratio);
for (int i = 0; i < n && maxWeight > 0; i++) {
if (obiecte[i].greutate <= maxWeight) {
maxWeight -= obiecte[i].greutate;
profitMax += obiecte[i].profit;
//printf("%d %lf\n", maxWeight, profitMax);
} else {
// printf("a");
p = (double)maxWeight / obiecte[i].greutate;
//printf("%d %lf %lf\n", maxWeight, profitMax, p);
maxWeight = 0;
// printf("%d\n",profitMax);
profitMax += obiecte[i].profit * p;
printf("%d\n",profitMax);
}
}
FILE *o = fopen("rucsac.out.txt", "w");
fprintf(o, "%lf", profitMax); // Write the profit with decimal places
fclose(o);
fclose(f);
return 0;
}