Sie sind auf Seite 1von 2

Knapsacktest.

java
//knapsack by greedy method
import java.util.*;
class Knapsack
{
int n;//number of objects
double p[];//array stores profit
double w[];//array stores weight
int capacity;//capacity of empt knapsack
void read()
{
Scanner kbd=new Scanner(System.in);
System.out.print("Enter Number Of Objects");
n=kbd.nextInt();
System.out.print("Enter Capacity Of Knapsack ");
capacity=kbd.nextInt();//create p & w array of size n+1
p=new double[n+1];
w=new double[n+1];//read array w & p from 1 to n
for (int i=1;i<=n;i++)
{
System.out.print("Enter Weight Of Object "+i);
w[i]=kbd.nextDouble();
System.out.print("Enter Profit Of Object "+i);
p[i]=kbd.nextDouble();
}
}//end of read method
void bubble()//method will sort p & w array in decreasing order of pi/wi
{
for(int i=n-1;i>=1;i--)
for(int j=1;j<=i;j++)
if(p[j]/w[j]<p[j+1]/w[j+1])
{
double t=p[j];
p[j]=p[j+1];
p[j+1]=t;
t=w[j];
w[j]=w[j+1];
w[j+1]=t;
}
}//end bubble
void fill()//fill knapsack & find profit
{
int i;
double x[]=new double[n+1];
for(i=1;i<=n;i++)
x[i]=0;
double profit=0;
double c=capacity;
for (i=1;i<=n;i++)
{
if (c-w[i]>=0)
{
c=c-w[i];
profit=profit+p[i];
x[i]=1;//object i is selected
}
else
break;
}
if (i<=n)
{
profit=profit+(p[i]/w[i])*c;
x[i]=c/w[i];
}
Page 1
Knapsacktest.java
//Now print Solution
System.out.println("Total Profit="+profit);
//Also print objects selected
i=1;
while (x[i]>0)
{
System.out.println(" Object"+i+" "+x[i]);
i++;
}
}//end fill
}//end knapsack
public class Knapsacktest
{
public static void main(String args[])
{
Knapsack k1=new Knapsack();
k1.read();
k1.bubble();
k1.fill();
}
}

Page 2

Das könnte Ihnen auch gefallen