You are on page 1of 32

SARDAR PATEL

UNI
VERSI
TY
SCHOOLOFENGI
NEERI
NG&TECHNOL
OGY
SardarPate
lKnowledgeCity,
Vill
ageDongari
ya
(
War
ase
oniroad)
,Pos
t-Chi
llo
d,Tahs he
el:
-Lal
barr
a,Dis
t-Bal
aghat
,M.
P.
481441

L
ABMANUAL
B.
Tec
h-4th

Nameo
fSubj
ect
:-Analys
isDes
igno
fAl
gor
ithm
Ses
sio
n-2022

Mr
.Ganes
hRao Mr.As
hishSoni Ms
.EktaRahangdal
e
DI
RECTOR HEADOFDEPARTMENT L
ABINCHARGE
L
isto
fEx
per
iment
s

S# L
abAs
signment Page
Number

1 Wr
iteap
rogr
amf
orI
ter
ati
veandRe
cur
siv
eBi
nar
ySe
arc
h

2 Wr
iteap
rogr
amf
orMe
rgeSo
rt

3 Wr
iteap
rogr
amf
orQui
ckSo
rt

4 Wr
iteap
rogr
amf
orSt
ras
sen’
sMat
rixMul
tip
lic
ati
on

5 Wr
iteap
rogr
amf
orHuf
fmanCo
ding

6 Writ
eap ro
gramf
orMi
nimumSp
anni
ngTr
eesus
ingKr
uskal
’s
al
gorit
hm

7 Writ
eap ro
gramf
orMi
nimumSp
anni
ngTr
eesus
ingPr
im’
s
al
gorit
hm

8 Wr
iteap
rogr
amf
orSi
ngl
eSo
urc
eSho
rte
stPat
h

9 Wr
iteap
rogr
amf
orf
loy
d-War
shal
lal
gor
ithm

10 Wr
iteap
rogr
amf
orTr
ave
lings
ale
smanp
rob
lem
L
ABEXPERI
MENT-1

AI
M

Wr
iteaPr
ogr
amf
orI
ter
ati
veandRe
cur
siv
eBi
nar
ySe
arc
h

I
NTRODUCTI
ON

Searc
has orte
dar raybyr epeate
dlydivi
dingt hesear
chinterv
alinhal f.Begi
nwi t
han
int
ervalco
veringthewho l
ear ray.Ifthev alueofthesearchkeyisl e
sst hantheitem
inthemiddleoftheint
er val,narro
wt heint er
valtothelowerhal
f .Otherwisenarrow
ittot
heup p
erhalf.Rep
e atedlycheckunti
lt hevaluei
sfoundorthei nterv
alise mpt
y.

AL
GORI
THM

I
TERATI
VEAL
GORI
THM

intfind( Ar ray Li
stlist,Doubl
etarge
t)
//Iterativeb inaryse archwillre
turnt
hei
nde
xoft
het
arge
tel
eme
nt,
els
eli
stl
engt
h
{
Booleanf ound=f als
e ;
intmi d;
intfirst=0;
intlas t=l ist.
s i
ze()-1;
while( first< =last&&! fo
und)
{
mid=( f i
r st+l ast)/2;
if(li
st.get(mi d).
equals (
targe
t))
found=t rue;
else
if(li
st.get(mi d)>t arget)
last=mi d-1;
elsef i
r st=mi d+1;
}
if(found)
returnmi d;
return- 1;
}
RECURSI
VEAL
GORI
THM

i
ntFind(Ar r
ay Li
stlist,Doub
letarget,Doub
l ef
irs
t,Do
ublelast
)
/
/Recursi
v ebinarys earchwillreturntheinde
xofthetargetele
ment
,el
sel
istl
engt
h
{
i
ntmid;
i
f(fi
rst>l ast)
re
turn-1;
mid=(fi
rs t+last)/2;
i
f(li
st.
get(mid).
equals(t
arget)
)
re
turnmi d;
i
f(li
st.
get(mid)<t arget)
re
turnfind(li
st,target,mid+
1,last)
;
re
turnfind(li
st,target,fi
rst,
mi d-
1);
}

PROGRAM

#i
ncl
ude
<st
dio
.h>
#i
ncl
ude
<co
nio.
h>

v
oidmai n()
{
inta[10],
n,i,
j,
temp ;
intbeg,end,mid,t
arge t;
clrsc
r (
);
printf(
"enterthet otalnumb ers:
?")
;
scanf("
%d",&n);
printf(
"enterthear r aye l
eme nt
s:?
");
for(i
=0;i
<n;i++
)scanf(
"%d",&a[i
])
;
for(i
=0;i
<n-1;i
++)
{
for(
j=0;j
< n-
i-1;
j++
)
{

if
(a[j
+1]<a[j
])
{
te
mp =a[j
];
a[
j]=
a[j+1]
;
a[j
+1]=
temp ;
}
}
}

printf(
"thes ortednumber
sare
:?"
);
for(i
=0;i
< n;
i++)
printf(
"%4d",a[
i]);
beg=a[0];
end=a[9];
mid=(beg+ e
nd)/2;
printf(
"\
ne ntert henumb
ertobesear
che
d:?
");
scanf("
%d" ,
&tar get
);

whi
le(beg<=end&&a[mid]!
=target )
{
if
(target<a[mid]
)end=mid-1;
e l
seb eg=mid+
1;
mid=(beg+end)
/2;
}i
f(a[
mid]==target)
{
printf(
"\
nthenumb erisf o
undatp osi
tio
n%2d"
,
mid)
;
}
els
e
{
printf(
"\
nthenumb erisno tfound:"
);
}
getch()
;
}

SAMPL
EOUTPUT

QUESTI
ONS

 Whatar
ere
cur
siv
eal
gor
ithms
?

 Whatar
eit
erat
iveal
gor
ithms
?

 Comp
arer
ecur
siv
eve
rsusi
ter
ati
veal
gor
ithms
.

 Whati
sthet
imec
omp
lex
ityo
fbi
nar
yse
arc
hal
gor
ithm?
 Whati
sthes
pac
eco
mpl
exi
tyo
fbi
nar
yse
arc
hal
gor
ithm?

L
ABEXPERI
MENT-2

AI
M

Wr
iteap
rogr
amf
orMe
rgeSo
rt

I
NTRODUCTI
ON

DivideandCo nquer
Divideandc onqueri sanimp ortantal gori
thmde signparadigmb asedonmul tibranched
recursion.A di vi
de and c o
nque r algo ri
thm wo rksb yrec ursivelyb r
eaki ng down a
problemi ntot woormo resub-problemso ft hesame( o
rr el
ate d)type,unti
lt heseb ec
o me
si
mp l
ee nought obes o
lveddirectly.Thes olut
ionstothesub-pr o
blemsar et henc ombined
togi vea s o
lutio
nt otheo riginalp roblem.Thistechni
quei st heb asiso fe ffic
ient
algorithmsf o rallki ndsofp roblems ,such ass ort
ing (
e .g.
,qui c
ksort,me r
ges or t
),
mult i
plyinglar genumb ers(e.gKar at s
uba),syntact
icanaly sis(e.g.
,top-
do wnp arsers),
andc omp uti
ngt hediscret
eFo uriertrans fo
r m(FFTs)
.

Merges o
rt
Merge s orti s an O(
n l o
g n) compar
iso
n-b
ased so
rti
ng algori
thm. In most
i
mp lementat
ionsitisstabl
e,meani
ng t
hati tpre
ser
vesthe i
nputo rde
ro fequal
ele
me ntsinthesort
edoutp
ut.Iti
sane x
amp l
eofthediv
ideandconqueralgo
rit
hmic
paradigm

AL
GORI
THM

St
eps
:
1. I ftheli
stiso
fl e
ngth0o r1,thenitisalreadys o
rte
d.Other
wise
2. Di v
idetheunso
rtedlisti
ntotwosub l
ist
so fabouthalfthes
ize
3. So rteac
hsubli
strecursi
velybyre-appl
yingme rgesort
.
4. Me rgethetwosubli
stsbackintoonesortedli
st

MERGE( A1,A2,A)
i.
← j1
A1[m+
1],A2[n+1]← INT_MAX
Fork←1t om +ndo
ifA1[ i
]<A2[j]
thenA[ k]← A1[i
]
i← i+ 1
els
e
A[k]← A2[ j
]
j← j+1
MERGE_SORT( A)
A1[
1..n/2]← A[ 1..n/
2]
A2[
1..n/2]← A[ 1+n/2..n]
MergeSort(A1)
MergeSort(A1)
MergeSort(A1,A2,A)

PROGRAM
//Mer
geSor
t

#include< i
o stream. h>
#include< conio.h>
inta[20];
voidme r
ge (int,i
nt,int)
;
voidme r
ge _so rt(
intl ow,
inthigh)
{
intmi d;
if(
low< high)
{
mid= (
low+ high)/2;
me rge_sor t
(low,mi d);
me rge_sor t
(mi d+1,high);
me rge(lo
w, mi d,
high) ;
}
}
voidme r
ge (intl ow,intmid,i
nthigh)
{
inth,i,
j,b
[20] ,
k;
h=low;
i=l
ow;
j=mid+1;

while(
(h<=
mid)&&(
j<=
high)
)
{
if
(a[h]
<=a[
j])
{
b[
i]=
a[h];
h++;
}
else
{
b[i]=
a[j];
j++;
}
i++;
}
if(h>mid)
{
for (
k=j;
k< =high;k++)
{
b[i]=
a[k];
i++;
}
}
else
{
for (
k=h;k<=mi d;k++
)
{
b[i]=
a[k];
i++;
}
}
for (
k=low;k< =high;
k++)a[k]
=b[
k];
}
voidmai n()
{clrscr(
);
intnum, i;
cout<<"Ho wmanyNo .UWantToSo rt(
Max20no.
)
"<<endl;
cin>>num;
cout<<"No w, PleaseEnt e
rt he("<<num<<
")number
s( ELEMENTS)
:
"<<
endl
;
for (
i=
1;i<=num; i++)
{
cin>>a[i];
}
me rge_s ort(1,
num);
cout<<endl ;
cout<<"So, thes ort
edl i
st(usi
ngMERGESORT)willbe:"<
< e
ndl;
for (
i=
1;i<=num; i++)
cout<<a[ i
]<< "";
get c
h();
}
SAMPL
EOUTPUT

L
ABEXERCI
SE-3

AI
M

Wr
iteap
rogr
amf
orQui
ckSo
rt

I
NTRODUCTI
ON

Quic
ksortisarecurs
ivesort
ingalgorit
hmf ollo
wi ngthe'
div
ideetimper
a'sc
heme .i
t
takesane l
ement(t
oken)ofthelis
tthati stosortandtransf
ersever
ye l
ementthat
smallerontheonesideande ve
rythi
ngt hatisbiggerontheothe
r.fo
rthewholelis
t,
thealgori
thmisusedonthet wopartsagainunt i
lthelis
tissort
ed.

AL
GORI
THM

procedurequi cksort(ar ray ,l


eft,right)
ifright>l eft
selectap ivoti ndex/ /(e.g.pivotIndex:=left+(r
ight-
left)
/2)
pivotNewI ndex: =par tition(array ,l
eft,right,piv
otIndex)
quicksort(
ar ray ,left,p ivotNewInde x-1)
quicksort(
ar ray ,pivotNe wI ndex+1, right)
functionp artition(arr ay ,lef
t,right,pivotIndex)
pivotValue: =ar ray [
piv otIndex]
swapar ray[pivotInde x]andar ray [
right]//Mo vepivottoend
storeIndex:=l eft
forif roml e fttor ight-1/ /left≤i<r ight
ifar ray[i
]≤p ivotVal ue
swapar ray[i]andar r ay [
storeIndex]
storeIndex:=s toreI nde x+1
swapar ray[storeInde x ]andar ray[ri
ght]//Mo vepivottoitsf
inalpl
ace
returns toreInde x

PROGRAM
#incl
ude <io
s t
r eam. h>
#incl
ude <conio.h>
inta[20];
voidquicksort (
int ,i
nt);
intpartitio
n(int ,
i nt);
voidmai n()
{
inti,j
,p ,
q,n,m;
clrscr();
cout<<"Ent erthee lentstosort
";
cin>>q;
cout<<"Ent er("
< <q<
<")Numb ers
"< <
endl
;
for(
i=0; i
< q;i++
)
{
c i
n> >a[i
];
}
p=0;
q= q-1;
n=p;
m= q;
quickso rt(n,m);
cout<<"So r t
e dNumb e r
sAr e"
<<endl;
for(
i=0; i
< q+1;i+
+)
{
c out <<a[
i];
}
getch();
}
voidquicksort (
intt op,intbottom)
{
//t o p=s ubscrip
to fbegi
nningofarray
//b ottom=s ubscripto
fe ndofarray

intmiddl
e;
if(t
op<b ot
tom)
{
middle=partit
ion(t
op,bot
tom);
quic
ksort
(to
p,middle);/
/sortfi
rstse
ction
quic
ksort
(middle+1,
bott
om);//sor
tseco
nds e
cti
on
}

}
/
/Functi
ontodeter
mi net
hepar t
iti
ons
/
/par t
iti
onsthearrayandreturnsthemi
ddl
esub
scr
ipt
i
ntp art
iti
on(
intto
p,intbo
tto
m)
{
intv=a[ t
op];
inti=top;
intj=b o
ttom+1;
intte
mp ;
do
{
do
{
j-
-;
}while(v<
a[j
])
;

do
{
i
++;
}whi
le(v>
a[i
])
;

if(i<j )
{
temp=a[ i]
;
a[i]=a[j]
;
a[j]=temp ;
}
}while(i<j )
;
a[t
o p
]=a[j
];a[
j]
=v;
returnj;//returnsmi
ddl
esub
scr
ip}

SAMPL
EOUTPUT

QUESTI
ONS
L
ABEXERCI
SE-4

AI
M

Wr
iteap
rogr
amf
orOp
timalMe
rgePat
ter
ns

I
NTRODUCTI
ON

Wewanttomer gesomes or
tedfi
leswher
et henumbero
freco
rdsare
{
12,
34,
56,
73,
24,
11,34,
56,
78,
91,
34,
91,
45}
.Whatistheopt
imalwaytomer
gethe
m?

AL
GORI
THM:

Ate
ver
yst
ageweme
rget
hef
ile
soft
hel
eas
tle
ngt
h.

Steps:
Createami nheapo ft hes etofe l
e ments
.
While(heaphasmo rethano nee l
eme nt)
{
Deleteami nimume leme ntfromt hehe ap,andsto
rei ti
nmi
n1;
Deleteami nimume leme ntfromt hehe ap,andsto
rei ti
nmi
n2;
Createano dewi ththef iel
ds(info,lef
t_l
ink,ri
ght_i
nk);
Letinfo.
node=mi n1+mi n2;
Letleft_
link.
node=mi n1;
Letright_l
ink_node=mi n2;
Insertnodewi thv al
ue di nf
ointot heheap;
}

s
tructtre
enode{
s
tructtre
enode*l
chi
ld,*
rchi
ld;
i
ntwe i
ght;
}
;
t
ypedefstruc
ttr
eenodeType
;

Type*Tre
e(i
ntn)
//l
isti
sagl ob
all
istofnsingl
eno de
//b
inarytre
esasdesc
r i
bedabove
.
{
for(i
nti =
1;i<n;i++){
Type*pt=ne wTy pe;
//Getane wt reeno de.
pt->lchil
d=L east(l
ist)
;//Me rgetwotre
eswith
pt->rchild=L east(l
ist);//small
estle
ngths
.
pt->we i
ght=( pt->lchil
d)->wei
ght
+(pt-
>rchild)
->weight ;
Insert
(li
st,*pt)
;
}
retur
n( Least(
list
));//Tr e
el ef
tinlistheme r
getr
ee.
}

PROGRAM

#include < i
ostream. h>
#include < c
onio.h>
voidmai n()
{
clrscr();
inti,k,a[ 10],
c[10],n,
l;
cout<< "Ent ert heno .ofe l
ement
s\t"
;
cin>>n;
cout<< "\nEnt ert hes or
tede l
mentsforo
pti
malme
rgep
att
ern"
;
for(i
= 0;i< n;
i++)
{
cout<< "\t";
cin>>a[ i];
}
i=0;
k= 0;
c[k]
=a[ i]+a[i+1];
i=2;
whi l
e (i<n)
{
k++;
if((
c[
k- 1] +a[i
])<=(a[i
]+a[
i+1]
))
{
c[k]
=c [k-1] +
a[i];
}
else
{
c[k]
=a[ i]+a[i+1];
i=i+
2;
while(i<n)
{k++;
if
((c
[k- 1]+
a[i])
<=(
c[k-2]
+a[
i])
)
{
c[
k]=c[k-1]+a[i
];
}
else
{
c[
k]=c[k-2]+a[i
];
}i
++;
}
}i
++;
}
k++;
c[
k]=c[k-1]+c[
k-2];
cout<<"\n\nTheo pti
mals umareasfol
lows.
..
.
..
\n\
n";
for(
k= 0;k<n-1;
k++)
{
cout<<c [
k]<<"\
t";
}
l=
0;
for(
k= 0;k<n-1;
k++)
{
l=
l+c[k];
}
cout<<"\n\nThee xte r
nalpathl
engt
his...
.
..
"<
<l;
getch();
}

PROGRAM

SAMPL
EOUTPUT

QUESTI
ONS
L
ABEXERCI
SE-5

AI
M

Wr
iteap
rogr
amf
orHuf
fmanCo
ding

I
NTRODUCTI
ON:

Givenas etofme ssageswithprobab i


lit
iesp1p 2pn,theHuffmancodetreei
s
constr
ucte
db yrecursi
velycombiningsubtrees:
1.Beginwithnt rees,eachcons
istso fas i
ngl eno
dec or
respo
ndingtoonemessageword,
withthewe ightofp i
2.Repeatunt i
lthereisonlyonet ree
_p i
cktwos ubtre
eswi thsmalle
s twe i
ghts
_comb i
nethe mb yaddingane wno deasr oot,andmaket hetwotreesit
schil
dren.
The
we i
ghtofthene wt reeisthesumo fthewe ightoftwosubtr
ees
Wi t
hahe ap ,eac
hs tepofcombiningt re
et akesO(lo
gn)t i
me,andthetotalt
imeisO(n
logn).

AL
GORI
THM

1.
2.So rts ource o utputsinde c
re asingo r
de roftheirp ro
b abil
itie
s
3.
4.Me r get hetwol east-p
r o
bable outputsintoas ingl
eo utputwho sep robabil
ity
isthes umo ft he c orrespondingp robabili
tie
s.
5.
6.I fthenumb ero fr e
mai ningo utputs i
smo rethan2, the ngot ostep1.
7.
8.Ar bitrar i
lyass i
gn0and1as codewo r
dsf orthetwor emainingo utputs
.
9.
10.Ifano utputisther esultof theme rgero ftwoo utputsinap receding
ste
p ,ap pendthec urrent c ode wordwi tha0anda1t oo bt
aint hec odeword
thet hep rece
ding o utputsandr epeats t
ep5.I fnoo utputisp r
e ce
de db y
another outputinap r
ec edingstep,thens t
op.
PROGRAM

#i
ncl
ude
<io
s t
r eam.h>
#i
ncl
ude
<st
r i
ng. h>
#i
ncl
ude
<mat h.
h>
#i
ncl
ude
<st
dli b
.h>
#i
ncl
ude
<conio.
h>

s
tructtree
{
c
hara[20];
i
nts;
s
tructtree*left,
*right;
}
*roo
t=NUL L
,*tt[
20]=
{NUL L},
*t
e mp,*
temp 2,
*t
2,*
ri,
*l
e;
s
tructpqu
{
intinfo;
c
hara[20];
s
tructpqu* ptr;
}
*fro
nt=NUL L,
*t,
*par,*t
1,*
p 1,
*p2;
s
tructpqu*fp (
intinfo)
{
s
tructpqu* p=NULL;
f
or(t
1=front;
t1->i
nfo<info&&t1!=
NUL L
;t1=t
1->pt
r)
{
p
=t1;
}
r
eturn(p);

}
v
oide nqu(chara[20]
,i
ntp)
{
t
=(s
truc tpqu*)mall
oc(
siz
eof
(st
ruc
tpqu)
);
s
trcpy(t->
a,a);
t
->i
nfo =p;
t
->ptr
= NUL L;
i
f(f
ront ==
NUL L)
{
f
ront=t;
}
e
lse
{
p
ar =
fp (
p);
i
f(p
ar ==NUL L
)
{
t
->ptr
= front;
f
ront
=t;
}
e
lse
{
t-
>ptr
=par-
>pt
r;
par-
>ptr
=t;
}
}
}

structp qu*de qu( )


{
t1=front ;
front= front->pt r;
returnt 1;
}
voi
di nfo(charc [2])
{
i
ntm= 0,
i;
temp 2= r
oo t;
whi l
e (st
r cmp (c,
te mp2->a)!
=0)
{
t2=temp 2->left;
for(i=0;i<strlen(
t2->a)
;i
++)
{
if(t2-
> a[i]==
c[0])
{
temp 2= temp 2->l
eft;
m= 1;
cout <
< "0";
br eak;
}
}
if(m!=1)
{
temp 2= temp 2->ri
ght;
cout <
< 1;
}
m= 0;
}
}

v
oidi
nse
rt(
)
{
c
hara1[
20]
,
b1[
20]
,
v1[
20]
;
i
nti ,
j,z
=0,l;
whi le(front!
=NUL L )
{
p1=de qu()
;
strcpy (
a1,p1->a);
l=p1->info;
p2=de qu()
;
i
f (
p 2==NUL L)
break;
strcpy (
b1,p2->a);
strcpy (
v1,a1);
temp =(structtre e*)
mal lo
c(si
zeof(
str
ucttr
ee))
;
strcpy (
temp ->a,
s trcat(
v1,
b1))
;
temp ->s=l+p2->i
nf o;
temp ->left=NUL L;
temp ->right=NUL L ;
temp 2=temp ;
root=temp ;
for(i=0;i
<z;)
{
i
f (
st rcmp (
tt[i]
->a,a1)==
0)
{
temp ->left=tt[
i]
;
for(l=i;
l<z;l
++)
{
tt[l
]=tt[
l+1];
}
i=0;
continue ;
}
elsei f(s
tr cmp(tt[
i]->a,
b1)
==0)
{
temp ->right=tt[
i];
for(l=i;
l<z;l
++)
{
tt[l
]=tt[
l+1];
}
i
=0;
cont i
nue ;
}
i
++;
}
i
f (
te mp -
>l e
f t
==NUL L )
{
le=(structt ree*)
mal l
oc(
size
of(s
tructtr
ee)
);
strcpy (
le->a,a1);
le->
le ft =NUL L;
le->
r ight =NUL L;
temp 2- >lef t=le;
}
if(
temp -> right ==NULL)
{
ri=(
str uc tt re e*)
mal lo
c(s
izeo
f(s
truc
ttr
ee)
);
strcpy (ri->a,b 1);
ri-
>le ft =NUL L;
ri-
>right =NUL L
;
temp 2- >right =ri
;
}
if(
fro nt !
=NUL L)
enqu(t emp 2-> a,t
e mp2-
>s);
tt[
z++]= temp 2;
}
}
voiddi s p(str uctt re
e* rt
)
{
if(
rt!=NUL L )
{
disp(
r t-> left )
;
cout<< "<< r
t ->a";
disp(
r t-> right );
}
}
voidmai n()
{
textmo de (
MONO) ;
inti=0, g,h,
p ,y,n;
charm[ 20],b [
20][2],
re;
while (1)
{
clrscr();

c
out
<< "
====
===
===
===
====
===
===
=="
;
c
out
<< "
HUFFMANCODI NG"
;
c
out
<< "
====
===
===
===
====
===
===
===
====
===
";
c
o
ut<<"
Enterthetotalnoofcharact
ers:"
;
c
in>
>n;
f
or(
i=0;
i<n;
i++
)
{
c
out
<< "
Enterthecharact
er:";
c
in>
>m;
s
trc
py (
b[i
],
m);
cout<
< "
Enterf
reque
ncyf
or"
<<m<
<":"
;
cin>>
g;
enqu(m,g)
;
}
inser
t()
;
disp(
root)
;
clrs
cr()
;

c
out
<<"
===
===
===
===
====
====
===
===
===
====
===
===
===
===
===
=";
c
out
<<"
Thecorres
pondingcode
sar e
..
..
.
";

c
out<<"==
===
====
===
===
===
===
===
===
===
===
===
===
===
===
===
===
===
=="
;
f
or(i
=0;i<
n;i
++)
{
c
out<<""
<<b[
i]<
<":";
i
nfo(
b [
i])
;
}
c
out<<"DOYOUWANTTOCONTI NUEYORN:" ;
c
in>>re;
i
f(r
e= =
'y'
|
|re
=='
Y')
c
ontinue;
e
lse
e
xit(
0);
}
}

PROGRAM

SAMPL
EOUTPUT

QUESTI
ONS
L
ABEXERCI
SE6

AI
M

Wr
iteap
rogr
amf
orKNAPSACKPr
obl
em

I
NTRODUCTI
ON

Theknaps ackpr oblemo rr ucksac kpr oblemi sap roblemi nc omb inatorialoptimization:
Give nas e tofi tems, eac hwi thawe ightandav alue ,
de te
rmi net henumb e rofe ach
it
e mt oinc ludei nac oll
e ctionsot hatt het ot
alwe ightislesst hanagi v enl i
mitandt he
totalv aluei sasl ar geasp o
ssible.I tde rivesitsnamef ro
mt hep r obl
emf acedb y
some onewhoi sconstrai ne dbyaf ixe d-
s i
zeknap sac kandmus tf i
lli twitht hemo st
usef ulitems .
Thep roblemo f t
enar isesi nr es
o urceal l
o c
ationwi thf inancialc onstraints.As imilar
prob le
mal soap pear sinc omb i
nat ory ,comp l
exityt heory,cryptograp hyandap pl
ied
mat he mat ic
s.
Int hef ollowing,wehav enki ndso fi tems ,1thro ughn.Eac hki ndo fitem ihasav alue
viandawei ghtwi .Weus uallyas sumet hatal lv aluesandwe i
ght sar eno nnegat i
ve.
Themax imumwe ightt hatwec anc ar ryint heb agi sW.
Themo stc ommo nf or mul ationo fthep rob l
emi st he0- 1knaps ac kpr oblem, which
restr i
ctst henumb erx io fc opi
eso fe achki ndofi te mtoz eroo ro ne.Mat he maticallythe
0-1-knaps ackp roblemc anb eformul atedas :

 maximiz
e

 sub
jectto
Thebo
undedknaps
ackpro
blemrest
ric
tsthenumb
erx iofc
opi
esofeac
hkindofi
temt
o
amaximuminte
gerv uec
al i.Mat
hemati
call
ythebounde
dknapsac
kpro
ble
mc anbe
for
mulat
edas:

 maximiz
e

 sub
jectto
Theunboundedknapsac
kprobl
emp lace
snouppe
rboundonthenumb
ero fc
opi
eso
feac
h
ki
ndofitem.
Ofparti
cularint
eres
tisthespec
ialcaseo
fthepro
blemwit
ht he
sepro
pert
ies
:

 i
t i
sade
cis
ionp
rob
lem,

 i
tisa0-1p
robl
em,

 f
oreac
hkind ofi
tem,
thewe
ighte
qual
sthev
al :wi=v
ue i.
Notic
et hati nthisspecialcas
e ,theprobl
emi se quivalenttothis:givenas etof
nonnegativeintegers,doesanys ubse
to fitaddupt oexac t
lyW?Or ,i
fnegativewe i
ghts
areal l
owedandW i sc hose
nt obez ero
,thepro b
l emi s
:givenas e tofintegers
, doe
sany
subsetaddupt oexactly0?Thiss peci
alcaseisc alledthes ubsets ump r
ob l
em.I nthe
fiel
do fcryp t
ographyt heterm knapsackproblem iso ft
e nusedtor e
ferspecif
icallyto
thesub s
ets ump roble
m.
Ifmul ti
pleknap sacksar eall
owe d,t
hep rob
lemi sbetterthoughto fastheb inp ac
king
probl
e m.

AL
GORI
THM

PROGRAM

#i
ncl
ude<iost
r eam. h>
#i
ncl
ude<conio.
h>
vo
idswap(fl
oatx []
,
intj )
{
floatte mp =x[j
];
x[j ]
=x[j
+1];
x[
j+1]
=temp;
}
vo
idmain()
{
clrscr(
);
floatw[ 5],p[
5],
x[5],m,u,
d[5]
,opt
im=0;
inti,j
;
cout<<"enterwe ight"<<endl;
for(i=0;i
< 5;
i++)
{
cin>>w[ i
];
}
cout<<"Ent erp r
of it"
<<endl;
for(i=0;i
< 5;
i++)
{
cin>>p [
i]
;
}
cout<<"entermax .capacity
"<<endl
;
cin>>m;
u=m;
for(i
=0;i<5;i
+ +)
{
x[i]
=0.0;
}
f
or(
i=
0;i<5;i
++)
{
d[
i ]
=p[
i]/w[i];
}
f
or(i
=0;i
< 4;
i++)
{
for(j=0;j
< 4;j
++)
{
if
(d[j]
< d[
j+1]
)
{
s
wap
(d,
j)
;
s
wap
(p,
j)
;
s
wap
(w,
j);
}
}
}
f
or(
i=
0;i<5;i
++)
{
if
(w[i]>u)
{
x[
i]=u/w[i]
;
}
else
{x[i]
=1;
u=u-w[i];
}
}

for(
i=
0;i
<5;
i++
)
{
c
out<<
x [
i]
<<""
;
}
for(
i=
0;i
<5;
i++
)
{
o
pti
m= opt
im+p[
i]
*x[i
];
}
cout
<<endl
<<"Opti
malsoluti
on=
"<<
opt
im<
<endl
;
getc
h()
;
}

PROGRAM

SAMPL
EOUTPUT
QUESTI
ONS

L
ABEXERCI
SE7

AI
M

I
mpl
eme
ntPr
im’
sal
gor
ithmt
ofi
ndmi
nimumc
osts
panni
ngt
ree

I
NTRODUCTI
ON

Prim'salgorit
hmi sanal gori
thmingr apht heorythatfindsami ni
mums panningtree
forac onnectedweightedgr aph.Thisme ansitfindsas ubsetoftheedgest hatformsa
treethatincludeseveryv e
rtex,
whe rethet ot
alwe ightofalltheedgesint hetreeis
minimized.Thealgorithmwasdi sco
veredi n1930b ymat hemati
cianVojtěchJar níkand
laterindependentl
yb yc omputerscie
ntistRo b
ertC.Pr imin1957andr ediscoveredby
EdsgerDijkstrain1959.The r
eforeitissome ti
me scalle
dt heDJPalgorithm, t
heJar ní
k
algori
thm, orthePr i
m- Jarníkalgori
thm

AL
GORI
THM

Givenac onnectedgrap hG=(V,E)andawe ightd: E-


>R+,findami nimums p
anningtree.
Prim'salgori
thmi skno wnt ob eago odal gorithmt of i
ndami ni
mums panningtree.
1.Seti=0,S0={u0=s}
,L(u0)
=0, andL (
v )
=i
nf i
ni t
yf orv< >u0.I f|
V|=1thenstop
, o
therwise
gotos t
e p2.
2.Fore achvinV\ Si,r
e pl
ac eL (
v)b ymin{ L
(v),dvui}.I
fL (v)isrepl
aced,
putal abe
l(L(v)
,
ui)onv.
3.Findav ertexvwhi chmi nimi ze
s{ L(
v):vi nV\ Si}
,sayui +1.
4.LetSi+1=Sic up{ui+1}.
5.Replaceib yi+1.I
fi =|
V|-
1t he nstop,otherwis egot ostep2

PSEUDOCODE
floatPr i m(intE[][
SI ZE],f l
oatcost[
][
SIZE],
intn,
intt
[]
[2]
)
{
intne ar [SIZE],j,k,L ;
let( k, L)b eane dgeo fmi nimumc os
tinE;
floatmi nc os
t=c ost[k][L]
;
t[1][1]=k;t [1][
2]=L ;
for( inti = 1;i<=
n;i++)/ /Initi
aliz
ene ar.
if( co st[i][L]<cost[i]
[k])ne ar[
i]=L;
elsene ar [i]=k;
ne ar [k]=ne ar[
L]=0;
for( i=2;i< =n-1;i++){/ /Findn-2additio
nal
//e dge sf o rt.
letjb eani ndexs ucht hatne ar[
j]!
=0and
cost [j][ne ar [
j]
]ismi ni mum;
t[i]
[1]=j ;t [
i][
2]=ne ar [j
];
mi nc o st=mi ncost+c ost[
j][
near[j
]]
;
ne ar [j]=0;
for( k=1;k< =n;k++)//Up dat enear[
].
if( (ne ar [k]!
=0)&&
(cost [k][ne ar[k]
]>cost[k][
j]))
ne ar [k]=j ;
}
re tur n(mi ncost
);
}

PROGRAM

#inc
lude<iost
ream.h>
#inc
lude<conio
.h>
i
ntG[20]
[20];
vo
idPrim(intnodes)
{
i
nts el
ect[
20],i,
j,k,
INFINITY=
30000;
i
ntmi n_di
st,v1,v2,
tot
al=
0;

f
or(
i=
0;i
<no
des;i++
)//Ini
tial
izet
hes
ele
cte
dve
rti
cesl
ist
s
ele
ct[
i]=0;

cout
< <
"\n\
nTheMinimalSpanni
ngTr
eeI
s:\
n";
s
elec
t [
0]=1;
for(k=1;k<=
node
s-1;k++
)
{
min_
dist=I NFINITY;
fo
r(i=0;i<=
nodes-1;i+
+)//Se
lectanedgesuchthatoneve
rte
xis
{//sel
ectedandotherisnotandtheedge
fo
r(j=0;j<=
nodes-
1;j++)/
/hastheleastwei
ght.
{
if(
G[i
][
j] && ( (
sel
ect
[i
] && ! se
lec
t[j
])||(!
sel
ect
[i
] &&
s
ele
ct[
j]
))
)
{
i
f(G[
i]
[j
]<mi
n_di
st)
//
obt
aine
dedgewi
thmi
nimum
wt
{
min_
dis
t=G[i]
[j
];
v1=i;
v2=j;/
/pi
cki
nguptho
sev
ert
ice
s
}
}
}
}
cout<<"
\nEdge("<
<v1<<""
<<v2<
<")
andweight="
<<min_
dis
t<<
endl
;
select
[v1]=sel
ect[
v2]=1;
total=tot
al+mi
n_dis
t;
}
c
out<<"
\n\n\tTo
talPathLengthIs="<
<to
t al
<<endl
;
}

v
oidmai
n()
{
i
ntnodes
;
i
ntv1,v
2,le
ngt
h,i
,j,
n;

c
lrsc
r (
);
c
out<<"\
n\tPrim'SAl gorithm\n";
c
out<<"\
nEnte rNumb e
ro fNo de sinTheGraph";
c
in>>nodes;
c
out<<"\
nEnte rNumb e
ro fEdge sinTheGraph";
c
in>>n;
f
or(i=0;i<
node s;i++)/
/I nit
ializethegraph
for(j
=0;j <nodes;j ++
)
G[i]
[j
]=0;
/
/ent
e ri
ngwe ightedgr aph
c
out<<"\
nEnte redge sandwe ights\n"
;
f
or(i=0;i<
n;i++)
{
cout<<
"\nEnt erEdgeb yV1andV2:";
cin>>v
1> >v2;
cout<<
"\nEnt erc orres
pondi
ngweight:
";
ci
n>>
length;
G[
v1]
[v2]=G[v2]
[v1]=l
engt
h;
}
get
ch()
;
co
ut<<"
\n\t
";
cl
rscr
();
Pri
m(nodes)
;
get
ch()
;
}

L
ABEXERCI
SE8

AI
M

I
mpl
eme
ntDi
jks
tra’
sal
gor
ithm.

I
ntr
oduc
tio
n

Dijkstra’salgo r
ithm.isagr ap hsear chalgor i
thm t hats olvesthes ingle-
sources hortest
pathp robl
emf oragr aphwi thno nne gativee dgep athcosts,outputti
ngas hortestp ath
tree.Thi salgorithmi so fte
nus e
di nr out
ing.
Foragi v
ens ourcev ertex(no de)int hegrap h,t heal gori
thm f i
ndst hep athwi thl owest
cost(i.e.thes hortestp ath)b et
we ent hatve rtexande v
er yotherv ertex.Itc anal sob e
usedf orf i
ndingc o s
tso fs hortestp athsfr om as inglev ertextoas i
nglede stination
vertexb ystoppingt heal gorithm o ncethes ho rtestp atht othede s t
inatio
nv e
rte xhas
beende termined.Fo re xamp le,ift hev ert
iceso ft hegr aphr epresentc it
iesande dge
pathc ostsrep r
e sentdr ivi
ngdi s
tanc esbetwe enp airso fc i
tiesc o
nne cte
db yadi rect
road,Di jkstr
a'sal gorithm canb eus edtof indt hes hor
testr outebe tweeno nec i
t yand
allo therc it
ies.Asar esult,thes hortes
tp athf i
rstiswi delyus edi nne t
wo rkr outing
protocols,mostno tablyI S-ISandOSPF( OpenSho rtestPathFi rst)
.Al gori
thm:L et'scall
theno dewear es tartingwi t
hani nit
ialno de.L etadi stanceo fa no deX b et he
distanc efromt hei nit
ialno det oit.

AL
GORI
THM

Ouralgo
rit
hmwi
llas
signs
omei
nit
ialdi
stanc
eval
uesandwi
llt
ryt
oimp
rov
ethe
m
st
ep-
by-s
tep.

1. As signt
oeverynodeadi
stanc
eval
ue.Se
titt
oze
rof
oro
uri
nit
ialno
deandt
o
inf
ini
tyf
orallot
hernodes.
2. Mar kal lno desasunv i
sited.Se ti
nitialno deasc ur rent.
3. Fo rcur rentno de , c
onside ral litsunv isi
tedne i
ghb oursandc alculat etheir
dist
anc e(fromt hei ni tialno de).Fo re xamp l
e ,ifcurrentno de( A)hasdi stanceo f6,and
ane dgec onne c
tingi twi thano the rno de(B)i s2, t
hedi st
anc et oBt hroughAwi l
lb e
6+2=8.Ifthisdi stancei slesst hant hep reviouslyrecorde ddi stanc e(
inf init
yi nthe
beginning,zerof ort hei nit
ialno de ),overwritet hedistance .
4. Whe nwear edo nec onside ringal lneighb oursoft hec ur rentno de, marki tas
visi
ted.Av isitedno dewi l
lno tb ec heckede ve ragain;itsdi stanc er e
co rdedno wi s
fi
nalandmi nimal .
.Sett heunv isi
te dno dewi ththes mal lestdistance(fromt hei nitialno de)ast hene x
t
"c
urr entnode "andc o ntinuef ro
ms t ep3.
1.
2.Whe n al lno de sar ev isited, algorit
hme nds.
3.

Dij
kst
r a'
sal go
r i
thm canbeimp l
ementedmo r
ee ff
ici
entlybystori
ngthegraphint
he
formo fadjacencyli
stsandus i
ngab inaryheap,pai
ringheap,orFib
onac
ciheapasa
pri
ori
tyque uet oimplementtheExtract
-Minfunct
ione f
fic
ient
ly.Wit
hab inar
yheap,
thealgori
thmr equiesO(
r (E|
| +
|V|
)lo V|
g| )time

PROGRAM

#include < iost


r eam>
#de f
ineI NFI NI TY999
usingname spaces td;
classGr ap h
{
private:
intadj Mat rix[15][15];
intpr ede ce ss
o r[15],
di s
tanc
e[15];
boolmar k[ 15];
intsour ce ;
intnumOf Ve rtices ;
public:
voidr ead( );
voidini tialize();
intge tClo sestUnmar kedNo
de();
voiddi jks tra()
;
voido utp ut()
;
voidp rint Path( i
nt );
};
voidGr ap h::
read( )
{
cout <<”Ent ert henumb e ro fv e
r tic
eso ft hegr aph(shouldb e>0)\
n”;
cin> >numOf Ve rtices;
//Numb ero fv e r
t icess houl dal way sgr eat erthanz ero
whi le(numOf Ve rtices< =0){
cout <<”Ent ert henumb e ro fv e
r tic
eso ft hegr aph(shouldb e>0)\
n”;
cin> >numOf Ve rtices;
}
//Readt headj ace ncymat rixfort hegr ap hwi th+v ewe ights
cout <<”Ent ert headj ace nc ymat r i
xfort hegr ap h\n”;
cout <<”Toe nteri nfinitye nter“ <<INFI NI TY< <endl;
for(inti =0;i<numOf Ve rtice s;
i++
){
cout <<”Ent ert he( +ve)we ight sfo rther ow“ <<i<<endl;
for(intj =0;j<numOf Ve rt i
c es;
j++){
cin> >adj Mat rix[
i][j]
;
whi le(adj Mat rix[i]
[j]
< 0){
cout <<”We i
ght ss houldb e+ ve.Ent erthewe ightagai n\n”;
cin> >adj Mat rix[
i][j]
;
}
}
}
//readt hes our ceno def ro mwhi chthes hortestp athst oothernode
shastob
efo
und
cout <<”Ent ert hes o
ur cev ertex\n”;
cin> >sour ce;
whi le((sourc e<0)&&( sour ce>numOf Verti ces-
1)){
cout <<”So urcev er texs ho uldb eb etween0and“ < <
numOf Verti
ces
-1<<e
ndl
;
cout <<”Ent ert hes o
ur cev ertexagai n\n” ;
cin> >sour ce;
}
}
voidGr ap h::
initialize()
{
for(inti =0;i<numOf Ve rtice s;
i++
){
mar k[i]=f alse ;
pr e
de ce ssor[i]=- 1;
distanc e [i
]=I NFI NITY;
}
distanc e
[/source ]
=0;
}
intGr ap h::
getClo sestUnmar kedNo de()
{
intmi nDi stance=I NFI NI TY;
intc lose stUnmar kedNo de ;
for(inti =0;i<numOf Ve rtice s;
i++
){
if((
!mar k[i]
)&&(mi nDi stanc e> =di st
anc e [
i])
){
minDi s t
anc e=di stance[i
];
closestUnmar kedNo de=i ;
}
}
retur nc los estUnmar kedNo de;
}
voidGr ap h::
di jkstra()
{
initi
al ize();
intmi nDi s tanc e=I NFINITY;
intc losest Unmar ke dNode;
intc ount=0;
whi l
e (
c ount<numOf Vertic
e s){
closestUnmar kedNo de=ge tCl ose stUnmar kedNode (
);
mar k[c l
o ses tUnmar kedNode ]=t r ue;
for(inti =0;i<numOf Ve rti
ces;i++){
if(
(!
mar k[i])&&( adj Mat r
ix[closes tUnmar kedNode ][
i]
>0)){
if(
dis tanc e[i]>di s
t ance[
close s
t Unmar kedNode]+adjMatri
x[c
loses
tUnmarke
dNode]
[i
]){
distanc e[i]=di stanc e[
clos
es tUnmar ke
dNo de]+
adj Matri
x[c
loses
tUnmarke
dNode
][i
];
prede ces sor[i]=c los es
tUnmar ke dNo de;
}
}
}
count ++;
}
}
voidGr ap h::
p rintPat h(i
ntno de )
{
if(
no de= =s our ce)
cout< <node << ”..
”;
elsei f(pre de cessor[node]==- 1)
cout< <”Nop at hf rom“ <<sourc e<< ”to“<<node<<endl;
else{
printPat h( pr edeces sor[
node]);
cout< <node << ”..
”;
}
}
voidGr ap h::
o utput()
{
for(inti =0;i<numOf Ve rti
ces;i++){
if(
i= =s our ce )
cout< <sour ce <<”.
.”<<source;
else
printPat h( i)
;
cout< <”-
> ”<< distanc e[i
]<<e
ndl ;
}
}
intmai n()
{
Gr aphG;
G.read()
;
G.dij
ks t
ra()
;
G.output(
);
return0;
}

L
ABEXERCI
SE-9

AI
M

Wr
iteap
rogr
amf
orf
loy
d-War
shal
lal
gor
ithm

AL
GORI
THM

PROGRAM

SAMPL
EOUTPUT

QUESTI
ONS

L
ABEXERCI
SE-10

AI
M
Wr
iteap
rogr
amf
orTr
ave
lings
ale
smanp
rob
lem

AL
GORI
THM

PROGRAM

SAMPL
EOUTPUT

You might also like