Cod sursa(job #3129241)

Utilizator yungxristfaur cristian yungxrist Data 13 mai 2023 15:23:44
Problema Problema rucsacului Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <stdio.h>
#define MAXN 5001
#define MAXG 10001

struct{
    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;
            }
        }
    }
    /*for (int i=0; i<n; i++)
    {
        printf("%d %d\n",obiecte[i].greutate,obiecte[i].profit);
    }
    */
    for (int i=0; i<n && maxWeight>0; i++)
    {
        if (obiecte[i].greutate<=maxWeight)
        {
            maxWeight-=obiecte[i].greutate;
            profitMax+=obiecte[i].profit;
            printf("%d %d\n",maxWeight,profitMax);
        }
        else
        {
            p=(double)maxWeight/obiecte[i].greutate;
            printf("%d %d %lf\n",maxWeight,profitMax,p);
            maxWeight=0;
            profitMax+=obiecte[i].profit*p;
        }
    }
    FILE *o=fopen("rucsac.out.txt","w");
    //fprintf(o,"%d",profitMax);
    fclose(o);
    fclose(f);
    return 0;
}