import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class KnapSack01 {
List b = Arrays.asList(10, 40, 30, 50);
List w = Arrays.asList(5, 4, 6, 3);
private int B[][];
public int getNum() { return w.size(); }
public KnapSack01(int M)
{
doAlloc(w.size()+1, M+1);
doAllot(w.size(), M+1);
printTable(w.size()+1, M+1);
}
public static void main(String args[])
{
KnapSack01 ks = new KnapSack01(10);
ks.listItems(10);
}
public void listItems(int M)
{
int i = getNum();
int k = M;
while (i > 0 && k >0)
{
if (B[i][k] != B[i-1][k])
{
System.out.println(i + " is in the knapsack");
i = i - 1;
k = k - (int)w.get(i-1);
}
else
i = i - 1;
}
}
public void printTable(int n, int M)
{
for (int i = 0 ; i < n; i++)
{
for (int j = 0 ; j < M; j++)
System.out.printf("%02d ", B[i][j]);
System.out.println();
}
}
public void doAlloc(int n, int M)
{
B = new int[n][M];
for (int i = 0 ; i < n; i++)
B[i][0] = 0;
for (int j = 0 ; j < M; j++)
B[0][j] = 0;
}
public void doAllot(int n, int M)
{
for (int i = 1 ; i <= n; i++)
{
for (int j = 0 ; j < M; j++)
{
if ((int)w.get(i-1) <= j &&
(((int)b.get(i-1) + B[i-1][j-(int)w.get(i-1)]) > B[i-1][(int)w.get(i-1)]))
{
B[i][j] = (int)b.get(i-1) + B[i-1][j-(int)w.get(i-1)];
}
else
B[i][j] = B[i-1][j];
}
}
}
}
import java.util.Arrays;
import java.util.List;
public class KnapSack01 {
List b = Arrays.asList(10, 40, 30, 50);
List w = Arrays.asList(5, 4, 6, 3);
private int B[][];
public int getNum() { return w.size(); }
public KnapSack01(int M)
{
doAlloc(w.size()+1, M+1);
doAllot(w.size(), M+1);
printTable(w.size()+1, M+1);
}
public static void main(String args[])
{
KnapSack01 ks = new KnapSack01(10);
ks.listItems(10);
}
public void listItems(int M)
{
int i = getNum();
int k = M;
while (i > 0 && k >0)
{
if (B[i][k] != B[i-1][k])
{
System.out.println(i + " is in the knapsack");
i = i - 1;
k = k - (int)w.get(i-1);
}
else
i = i - 1;
}
}
public void printTable(int n, int M)
{
for (int i = 0 ; i < n; i++)
{
for (int j = 0 ; j < M; j++)
System.out.printf("%02d ", B[i][j]);
System.out.println();
}
}
public void doAlloc(int n, int M)
{
B = new int[n][M];
for (int i = 0 ; i < n; i++)
B[i][0] = 0;
for (int j = 0 ; j < M; j++)
B[0][j] = 0;
}
public void doAllot(int n, int M)
{
for (int i = 1 ; i <= n; i++)
{
for (int j = 0 ; j < M; j++)
{
if ((int)w.get(i-1) <= j &&
(((int)b.get(i-1) + B[i-1][j-(int)w.get(i-1)]) > B[i-1][(int)w.get(i-1)]))
{
B[i][j] = (int)b.get(i-1) + B[i-1][j-(int)w.get(i-1)];
}
else
B[i][j] = B[i-1][j];
}
}
}
}
No comments:
Post a Comment