Pagini recente » Cod sursa (job #2607347) | Cod sursa (job #438550) | Cod sursa (job #1652424) | Cod sursa (job #225652) | Cod sursa (job #3133621)
#include <stdio.h>
typedef struct
{
int weight;
int value;
} obiect;
int rucsac_greedy(obiect *obiecte, int N, int G)
{
for (int i = 0; i < N - 1; i++)
{
for (int j = i + 1; j < N; j++)
{
double rata1 = (double)obiecte[i].value / obiecte[i].weight;
double rata2 = (double)obiecte[j].value / obiecte[j].weight;
if (rata1 < rata2)
{
// Swap
obiect temp = obiecte[i];
obiecte[i] = obiecte[j];
obiecte[j] = temp;
}
}
}
int totalValue = 0;
int totalWeight = 0;
for (int i = 0; i < N; i++)
{
if (totalWeight + obiecte[i].weight <= G)
{
totalWeight += obiecte[i].weight;
totalValue += obiecte[i].value;
}
}
return totalValue;
}
int main(void)
{
int N, G;
FILE *f,*g;
f=fopen("rucsac.in","r");
g=fopen("rucsac.out","w");
fscanf(f,"%d %d", &N, &G);
obiect obiecte[N]; //vector de obiecte
for (int i = 0; i < N; i++)
{
fscanf(f,"%d %d", &obiecte[i].weight, &obiecte[i].value); // greutate obiect i valoare obiect i
}
fprintf(g,"%d", rucsac_greedy(obiecte, N, G));
fclose(f);
fclose(g);
return 0;
}