Cod sursa(job #3133707)

Utilizator yungxristfaur cristian yungxrist Data 26 mai 2023 16:53:00
Problema Problema rucsacului Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <stdio.h>
#include <stdlib.h>
#define MAXN 5001
#define MAXG 10001

struct rucsac{
    int greutate, profit;
    double ratio;
} obiecte[5001], aux;

int compare(const void *a, const void *b) {
    const struct rucsac *obj1 = (const struct rucsac*)a;
    const struct rucsac *obj2 = (const struct rucsac*)b;
    
    // Compare the ratios of the objects and return the result
    if (obj1->ratio < obj2->ratio)
        return 1;
    else if (obj1->ratio > obj2->ratio)
        return -1;
    else
        return 0;
}
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]),compare);
    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, "%d", profitMax);  // Write the profit with decimal places
    fclose(o);
    fclose(f);
    
    return 0;

}