Greedy Method (Knapsack & Prims)
Greedy Method (Knapsack & Prims)
import java.util.Scanner;
public class Kanpsack
{
public static void main(String[] args)
{
System.out.println("Enter Weights:");
for(i=1;i<=n;i++)
w[i] = sc.nextFloat();
for(i=1;i<=n;i++)
c[i] = p[i]/w[i];
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i;j++)
{
temp = w[j];
w[j] = w[j+1];
w[j+1] = temp;
temp = p[j];
p[j] = p[j+1];
p[j+1] = temp;
}
}
}
for(i=1;i<=n;i++)
profit = profit + (p[i] * x[i]);
System.out.println("\n\t Maximum Profit = "+profit);
}
Output:
Enter No. of Objects: 3
Enter Weights:
18
15
10
Enter Profits:
25
24
15
Enter Knapsack Size
20
x[1] = 1.0
x[2] = 0.5
x[3] = 0.0
Maximum Profit = 31.5
2) Find the optimal solution for the 0/1 knapsack problem making use of Greedy approach . Consider-
n=4
w = 5 kg
(w1, w2, w3, w4) = (2, 3, 4, 5)
(b1, b2, b3, b4) = (3, 4, 5, 6)
Max Profit??
2. Find Minimum Cost Spanning Tree of a given undirected graph using Prim's
algorithm. Implement the program in Java language.
import java.util.Scanner;
public class Prims {
public static void main(String[] args) {
if(visited[u] == 0 || visited[v] == 0)
{
System.out.println("\n\t"+ne+" Edge ["+a+","+b+"] = "+min);
ne++;
mincost += min;
visited[b] = 1;
}
cost[a][b]=cost[b][a]=999;
}
System.out.println("\n\tMinimum Cost = "+mincost);
}
}
Output:
Minimum cost of spanning tree??