You are on page 1of 2

1:

2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:

#include <iostream>
#include <stdlib.h>
//alt ex: alg lui dijkstra, grafuri
using namespace std;
#define NMAX 6
typedef struct{
int castig;
int greutate;
int index;
} obiect;
int indiciObiecteSelectate[NMAX];

void sortareInterschimbare(obiect obiecte[], int nrObiecte){//ordonam obiectele


in sens descrescator, dupa eficienta
17:
float eficienta[NMAX];
18:
int i;
19:
20:
for(i = 0; i < NMAX; i++) eficienta[i] =
(float)obiecte[i].castig/obiecte[i].greutate;
21:
22:
bool sortat = false;
23:
24:
while(!sortat){
25:
sortat = true;
26:
for(i = 0; i < nrObiecte; i++)
27:
if(eficienta[i] < eficienta[i+1]){
28:
obiect temp;
29:
temp = obiecte[i];
30:
obiecte[i] = obiecte[i+1];
31:
obiecte[i+1] = temp;
32:
eficienta[i] = (float)obiecte[i].castig/obiecte[i].greutate;
33:
eficienta[i+1] =
(float)obiecte[i+1].castig/obiecte[i+1].greutate;
34:
sortat = false;
35:
}
36:
}
37: }
38:
39: void umplereRucsac(obiect obiecte[], int nrObiecte, int greutateSac){
40:
int greutateTemp = 0, i, j = 0;
41:
for(i = 0; i < nrObiecte; i++) indiciObiecteSelectate[i] = 0;
42:
43:
float eficienta[NMAX];
44:
for(i = 0; i < NMAX; i++) eficienta[i] =
(float)obiecte[i].castig/obiecte[i].greutate;//eficienta dupa ordonare
45:
46:
for(i = 0; i < nrObiecte; i++)
47:
if((greutateTemp + obiecte[i].greutate) <= greutateSac){
48:
greutateTemp +=obiecte[i].greutate;
49:
indiciObiecteSelectate[j++] = i;
50:
}
51:
52:
//afisam continutul sacului
53:
for(int k = 0; k < j; k++){
54:
cout << "Obiectul " << obiecte[indiciObiecteSelectate[k]].index ;
55:
cout << "\tcastig " << obiecte[indiciObiecteSelectate[k]].castig ;
56:
cout << "\tgreutate " << obiecte[indiciObiecteSelectate[k]].greutate;

57:
cout << "\tsatisfactie selectie " << eficienta[k] << endl;
58:
}
59: }
60:
61:
62:
63: int main(){
64:
obiect obiecte[NMAX] = {{4,5,1}, {2,3,2}, {3,4,3}, {1,2,4}, {5,6,5}, {6,7,
6}};
65:
int greutateRucsac, nrObiecte;
66:
67:
cout << "Introduceti numarul de obiecte, <" << NMAX << ": ";
68:
cin >> nrObiecte;
69:
70:
cout << "Introduceti greutatea rucsacului: ";
71:
cin >> greutateRucsac;
72:
73:
sortareInterschimbare(obiecte, nrObiecte);
74:
75:
umplereRucsac(obiecte, nrObiecte, greutateRucsac);
76:
77:
system("PAUSE");
78:
return 0;
79: }
80:

You might also like