贪心算法——背包问题
程序代码
public class GreedyPackage {
private int MAX_WEIGHT = 150 ;
private int [ ] weights = new int [ ] { 35 , 30 , 60 , 50 , 40 , 10 , 25 } ;
private int [ ] values = new int [ ] { 10 , 40 , 30 , 50 , 35 , 40 , 30 } ;
private void packageGreedy ( int capacity, int [ ] weights, int [ ] values) {
int n = weights. length;
double [ ] r = new double [ n] ;
int [ ] index = new int [ n] ;
for ( int i = 0 ; i < n; i++ ) {
r[ i] = ( double ) values[ i] / weights[ i] ;
index[ i] = i;
}
double temp = 0 ;
for ( int i = 0 ; i < n - 1 ; i++ ) {
for ( int j = i + 1 ; j < n; j++ ) {
if ( r[ i] < r[ j] ) {
temp = r[ i] ;
r[ i] = r[ j] ;
r[ j] = temp;
int x = index[ i] ;
index[ i] = index[ j] ;
index[ j] = x;
}
}
}
int [ ] w1 = new int [ n] ;
int [ ] value1 = new int [ n] ;
for ( int i = 0 ; i < n; i++ ) {
w1[ i] = weights[ index[ i] ] ;
value1[ i] = values[ index[ i] ] ;
}
int [ ] x = new int [ n] ;
int maxValue = 0 ;
for ( int i = 0 ; i < n; i++ ) {
if ( w1[ i] <= capacity) {
x[ i] = 1 ;
capacity = capacity - w1[ i] ;
maxValue += value1[ i] ;
}
}
System. out. println ( "总共放下的物品数量:" + Arrays. toString ( x) ) ;
System. out. println ( "最大价值为:" + maxValue) ;
}
public static void main ( String[ ] args) {
GreedyPackage g = new GreedyPackage ( ) ;
g. packageGreedy ( g. MAX_WEIGHT, g. weights, g. values) ;
}
}
运行结果