Greedy algorithms always make the best choice for the moment. That is to say, the greedy algorithm does not take the overall optimization into consideration. All it makes is a local optimal choice in a certain sense.
[Cpp]
# Include <stdio. h>
# Define M 5
Struct node {
Float value;
Float weight;
Int flag;
} Node [M], temp;
Float Value, curvalue = 0;
Float Weight, curweight = 0;
// Sort by cost effectiveness
Void sort (){
Int I, j;
For (I = 0; I <M-1; I ++ ){
For (j = I + 1; j <M; j ++ ){
If (Node [I]. value/(float) Node [I]. weight) <Node [j]. value/(float) Node [j]. weight ){
Temp = Node [I];
Node [I] = Node [j];
Node [j] = temp;
}
}
}
}
// Loading Methods
Void load (){
Int I;
For (I = 0; I <M; I ++ ){
If (Node [I]. weight + curweight) <= Weight ){
Curvalue + = Node [I]. value;
Curweight + = Node [I]. weight;
Node [I]. flag = 1;
} Else {
Node [I]. flag = 0;
}
}
}
// Output the result
Void putout (){
Int I;
Printf ("the weight of the selected item is :");
For (I = 0; I <M; I ++ ){
If (Node [I]. flag ){
Printf ("%. 2f", Node [I]. weight );
}
}
Printf ("\ n total value: %. 2f", curvalue );
}
Int main (){
Int I;
Printf ("Enter the weight and value of the item: \ n ");
For (I = 0; I <M; I ++ ){
Printf ("Enter the weight and value of item % d", I + 1 );
Scanf ("% f", & Node [I]. weight, & Node [I]. value );
}
Printf ("\ n enter the volume of the backpack :");
Scanf ("% f", & Weight );
Sort ();
Load ();
Putout ();
Return 0;
}
# Include <stdio. h>
# Define M 5
Struct node {
Float value;
Float weight;
Int flag;
} Node [M], temp;
Float Value, curvalue = 0;
Float Weight, curweight = 0;
// Sort by cost effectiveness
Void sort (){
Int I, j;
For (I = 0; I <M-1; I ++ ){
For (j = I + 1; j <M; j ++ ){
If (Node [I]. value/(float) Node [I]. weight) <Node [j]. value/(float) Node [j]. weight ){
Temp = Node [I];
Node [I] = Node [j];
Node [j] = temp;
}
}
}
}
// Loading Methods
Void load (){
Int I;
For (I = 0; I <M; I ++ ){
If (Node [I]. weight + curweight) <= Weight ){
Curvalue + = Node [I]. value;
Curweight + = Node [I]. weight;
Node [I]. flag = 1;
} Else {
Node [I]. flag = 0;
}
}
}
// Output the result
Void putout (){
Int I;
Printf ("the weight of the selected item is :");
For (I = 0; I <M; I ++ ){
If (Node [I]. flag ){
Printf ("%. 2f", Node [I]. weight );
}
}
Printf ("\ n total value: %. 2f", curvalue );
}
Int main (){
Int I;
Printf ("Enter the weight and value of the item: \ n ");
For (I = 0; I <M; I ++ ){
Printf ("Enter the weight and value of item % d", I + 1 );
Scanf ("% f", & Node [I]. weight, & Node [I]. value );
}
Printf ("\ n enter the volume of the backpack :");
Scanf ("% f", & Weight );
Sort ();
Load ();
Putout ();
Return 0;
}