Pagini recente » Cod sursa (job #2780791) | Cod sursa (job #1436535) | Cod sursa (job #1327696) | Cod sursa (job #559123) | Cod sursa (job #3133711)
#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;
}