Cod sursa(job #3133711)

Utilizator sxdoesnotexistVarga Sergiu sxdoesnotexist Data 26 mai 2023 17:04:23
Problema Problema rucsacului Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <stdio.h>
#include <stdlib.h>

#define NRMAX_OBJ 5000

void fault(){

    printf("Something went wrong ;(\n");
    exit(0);
}

typedef struct _obiect {

    double weight;
    double profit;
    double ratio;
}object;

int cmpObj(const void* el1, const void* el2 ){

    object ob1 = *(object*) el1;
    object ob2 = *(object*) el2;

    if( ob2.ratio-ob1.ratio!=0 )
        return ob2.ratio-ob1.ratio;
    else
        return ob1.profit-ob2.profit;
}



int main() {

    object arr[NRMAX_OBJ];
    FILE* f = fopen("rucsac.in","r");
    FILE* g = fopen("rucsac.out","w");

    if( f==NULL || g==NULL ){
            printf("Error opening the files\n");
            exit(0);
    }

    int maxG,N;
    int Pmax=0;

    if ( fscanf(f,"%d %d",&N,&maxG)!=2 )
            fault();

    for ( int i=0; i<N; i++ ) {

        if ( fscanf(f,"%lf %lf",&arr[i].weight,&arr[i].profit)!=2 )
            fault();

        arr[i].ratio = (double) arr[i].profit / arr[i].weight;      
    }

    qsort(arr,N,sizeof(arr[0]),cmpObj);

    int crtG=0;
    for(int i=0; i<N; i++) {

        if( crtG + arr[i].weight <= maxG ){
                
                crtG += arr[i].weight;
                Pmax += arr[i].profit;
        }
        else if ( crtG + arr[i].weight > maxG ){

            double fract = (maxG-crtG)/arr[i].weight;
            Pmax += arr[i].profit*fract;
            break;
        }
    }
   // printf("%d\n",crtG);
    fprintf(g,"%d",Pmax);

    return 0;
}