You are on page 1of 26
Dept. of CSE — T Program 6 Implement in Java, the 0/1 Knapsack problem using : > Dynamic Programming method > Greedy method ALGORITHM : ALGORITHM MFKnapsack(i, i) . // Implements the memory function method for the knapsack problem // Input: A nonnegative integer i indicating the number: ofthe first items being 17 considered and a nonnegative integer j indicating the knapsack’s capacity 1/ Output: The value of an optimal feasible subset ofthe first items 11 Note: Uses as global variables input arrays Weights{1.}, Values{.n, and table 11 110.2, 0.17 whose entries ar initialized with -'s exeePt for row 0 and column 0 initialized with 0°s if Mi, <0 ij < Weights] valié— MFKnapsack(i~ 1.) ase » Ssvalue — max(MFKnapsack( = 1,j), Values{i) + <) MFKnapsack(i-1,j-Weights{i))) Mi fle value return, Mi, /] DAA Laboratory Manual (18CSL47) & scanned with OKEN Scanner yt. of CSE errr ene eel HE pg ALGORITHM GreedyKnapsack(foat m, int ) Mordered such that Plijy{i] > d Weights respectively of the n objects i/the solution vector 7 { float u =m; for (i= 1;i Wy) continue; aU) = 10; é u-= ws hoa CODE: i import java-util.*7 public class Knapsack { static int~[)p\¢ staticwint ((]# static int []x =new int (50]+ static\int (Jt =new int (50]7 static double maxprofity static int n,m, i,j static void dynamicknapsack(int ny int w(J, int p(], int m) i int () (v= new int (n+2) (m1) 7 for(ie;icensitt) v(i] (0]=07 for (j=07 j<-ms j++) vy(0] (3107 48 DAA Laboratory Manual (18CSL47) Page & scanned with OKEN Scanner KS.1T for (ie1sicensit+) for(je1i3 setv(s) (3) ev.) ( x)=) snd-wlhd? , ies ) t 1 atem-oug,printin("the solution Vector for Dynante Method ie a ae ror inafPeniiy f ‘System. out.print (x(i]+"\t")7 ystea.gutyprsaein("\n")7 14 stati®gint max(int a, int b) statidyint max return (a>b)?a:b ) Jeatic void greedyinapsack(int n, int w(J, iit pt], int m) ( int re=m bubblesort (n,W,P,t)# for et) if(w{t{ill>re) continue; DAA Laboratory Manual (18CSL47) & scanned with OKEN Scanner of CSE x{tliy KS.LT Fo-=wit(t}); MAPPED TELL, System.out.printin( “emaxprofit) ; system. out.printin(» for (i=Lsicensiss) System. out print (x{i)+m\em) ; static void bubblesort (int n,4 Ant w(,int p(],int t(J) int temp; for (i=1;i with and its ertex vin V Initialize(Q) Vntialize vertex priority quewe 1° empty for every vertex vin do dy— oo; py nll ae i switialige vertex priority in the priority queue Insert(Q, v, dy) aux 0; Decrease(Q, sd) spas priority of 3 with ds VO for i 0to|/-1do uy" — DeleteMin(Q) ldelete the minimum priority element Vre—VrU {u"} | for every vertex 1 in Vrthat is adjacent to u’ do if det wt’, y) "+j+"="4aist (5}) 7 DAA Laboratory Manual (18CSL47) & scanned with OKEN Scanner Seer the cost adjacency matrix, '9999' for no direct path oo 9999 45 © 9999 go 0 28 9999 20 9999 999 0 20 9999 9999 398 io 99990 35. 9999 999 9999 9999 0 9999 9999 0 ggo9 9999 9999 4 gnter the starting vertex: 6 shortest path from starting vertex to other vertices are 9 enter the no. of nodes : sggg9t for no direct path — Os 377 3 0O 4 2 9999 4 0 8 He enter the starting vertex? 3 tex to other vertices are . Shortest path from starting Vo Lo ee Page 56 & scanned with OKEN Scanner Dept. of CSE Program 8 d oral rind Minimum cost Spanning Tree of a given connected undlrecton' g Kruskal's algorithm. Use Union-Find algorithms In your Clete ph using ALGORITHM Kruskal(G) I/ Kruskal’s algorithm for constructing a minimum s Input: A weighted connected graph G = 1/ Output: Er, the set of edges composing a minimum spa panning tree wnning tree of G Sort E in non-decreasing order of the edge weights w(e1) = ‘ ‘nOutput: Er, the set of edges composing a minimum spanning ee of Vem {v0} ithe set of tree vertices can be initialized ‘vith any vertex Er-O for i— 1 to |/-1do find a minimam-weight edge e” = 6 vyis in Vrand wis in V- Vr Vre— VrU tu’) Ere ErU(e} return Er » u') among all the edges (v, w) such that CODE: inport java-util-scanner? public class.P9 { ing () 2299) publie, stati 1 ¢ void main (StF fine mys? : me md 2e gen sme (20) 208 aang a no 9 vertices")i ee f Pee nonetne 07 capeineantrenear tne SORE ajaconcy massa, '9999" £0" M2 direct path ")+ Tor i=tsseens3e") for J=1IM Ig, pont tat! cost (i) (3) prims (costs? DAA Laboratory Manual (1 & scanned with OKEN Scanner Dep CSE static void prins (int cost(] {1/int #) i int ()venew int (1017 =0,noe=1? int min,p,q,i,3, f1ag-0-mincost=0r v(ulets e following edges"), systen.out-printin("The spanning tree has the f o . while (noe!=n) - 999; flag=0; 4 for (p=lipeenipt+) for(a=trqcensa++) { if (pera) continues ) 6 (tq) !=1)) 4£((cost [p] [q] new int (10) (101; Scanner read = new Scanner(System.in); System. out.printin(Menter the no. of nodes"); n=read.nextInt ()7 out.peintln ("enter the cost adjacency matrix, '9999" for no system direct path"): for (i=1;icensi++) : a1: j 0, 1<=j<+n. else if (s+iv[k]+w{k+1] <= m) SubO{Sub(s+w{k], k+1, r-w[k]); // Generate right child and evaluate By if ((str-w[k] >= m) && )stw[k1] <= m)) { 4 x{k] = 0; SumOSub(S, k+l, rw{kD; CODE: import java.util.Scanners Public class P11 { static int d,flag-0s static int []S static, int []x new int (1017 new int (10]7 'AA Laboratory Manual (18CSL47) sal & scanned with OKEN Scanner sf CSE eH) eatie vod sunofaub(int #4Rt win i int iz xtelele a for (i=isiceksit+) systen.out .printin() 7 else : srstk)astnet} oa : Lele pob laws UKD RII SERD)? Le ((etr-stkdoad) a6 (StS [ke] <0) (i001 secant, 2-808) A ) public static void main(String () args) cl int in, sum Scanner read= new. Scanner (System.in) 7 systen.out-printin ("enter the no, of elements in the set"); neread.nextint (1+ system.out printin ("enter the set in increasing order"); for (i= fi¢) tue UteMOUE-PELntIn ("no subset possible") ; fi system. out .printin( sunofsub (0, 1, sum) ; if(flage=0} System.out.printin(™ "The possible subsets are"); ‘no subset possible ")7 i & scanned with OKEN Scanner enter the no. ¢ Of elements in the set enter the set in increasing order i 2 eer a enter the max subset value The possible subsets ar 2 2 6 ee enter the no. of elements in the set 5 enter the set in increasing order 2 2 5 6 8 enter the max subset value 25 no subset possible enter the no. of elements in the set 4 enter the set in increasing order 3567 enter the max subset value 15 The possible subsets are 3 5 7 enter the no. of elements in the set 4 enter the set in increasing order 3567 enter the max subset value 2 no subset possible a & scanned with OKEN Scanner s t. of CSE Program 12 Design and implement i Graph G of a vertices using b in a connected unr ecteg in Java to find yacktracki ALGORITHM: ation of backtracking to find all void Hamiltonian (int K) stored as anadjacency r JI This program uses the recursive formul ‘7 the Hamiltonian cycles of 2 graph. The Lge ‘1 matrix G[l:n] [I:a}. All cycles begin at 92 ic 1. 4 { do { // Generate values for x} NextValue(¥) 5 Assign a les if (x{KD) return; fk=m) ( for (int cout <<"1\n"s al next value t6 xfK]s, ican; i+) cout << xli] << he 3 else Hamiltonian (K+1); } while (1); } void NextValue(int K) 1 a€ ys xfk-1} 8a path ofl distinct vertices. I x[k]=—0, then no vertex has as yet ‘7 been assigned to x{k]. After execution x[k] is assigned to the next highest 77 numbered vertex which i) does not already appear in x{1), x[2}.. x[k-1]; and is connected by an edge to x{K-1]. Otherwise x[k]=0. Ifk—=n, then /1in addition x{K] is Connected to x1]. { aol \ sk) 2Gtk}+1) % (a4); Nest vertex if (Ix{k]) return; it (Glx{k-1}] (KID {_Isthere an edge? for (it 1; j")7 a A Laboratory Manual (18CSL47) for ( & scanned with OKEN Scanner Ks Dept. of CSE system.out Print (xt)? , else : ncyctetG ny K+)? ) public static void main(steingt] args) ( int i,j m7 int (1{1 G = new int (25) (2517 scanner read = new Scanner (system-in)7 system.out.printin("Enter the number of vertices of the graph"); neread.next int () trix’ systen.out.printin("Enter the Path adjacency, ma for (istjicensitt) ‘ for (jetsjeons344) ( Gli] [j)-read-nextint (17 x(i)=07 ' | x(lely systen-out.print1n(" \n Hamiltonian Cycles ar A_cycle(Gyni2) DAA Laboratory Manual (I8CSL47) & scanned with OKEN Scanner Dept. of CSE Enter the number of vertices of the graph Enter the Path adjacency matrix Hamiltonian cycles are I-92-->8--> 7-2 6--9 5-94-9391 Enter the number of vertices of the graph Hamiltonian Cycles are p6-->5-->3-Pd-—>d Aan? apgenp 6-->S--P4--D3-—P 1 >5-->4-->1 1ned3--92-->6 Tsp3-o3ga-9 5-96-21 Bpdena3--9 5-96-9271 Page 74 Daa Laboratory Manual (18CSL47) & scanned with OKEN Scanner

You might also like