0% found this document useful (0 votes)
34 views58 pages

DAA Revision Notes

The document outlines various concepts related to algorithms, including definitions of terms like natural language, pseudocode, and asymptotic analysis. It discusses performance metrics such as time and space complexity, recurrence relations, and the Master Theorem for solving algorithmic problems. Additionally, it covers data structures like trees and graphs, as well as operations associated with them.

Uploaded by

shaikakramim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views58 pages

DAA Revision Notes

The document outlines various concepts related to algorithms, including definitions of terms like natural language, pseudocode, and asymptotic analysis. It discusses performance metrics such as time and space complexity, recurrence relations, and the Master Theorem for solving algorithmic problems. Additionally, it covers data structures like trees and graphs, as well as operations associated with them.

Uploaded by

shaikakramim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Date

Page No, ...D.!........


UNIT:- 01 Introdclion.

inatnclion thad toks enput,


a déquence ell defined

Fnknes
llgo mual krmnate ofr finile no.g, skcps, canl goon fefe

2-Debiaitents
kadh slep mual be cleas wwbigucusly daioed

3.

4 Output
Alao Chold roduce at leasl 1 Bukpal by pace Ming lnpal data

bach Siep kheuld ke snpl & detly Sayplan lalle.

•Speficatin
is malus dsenoing algo in omal ng Methnads

Roll No. Lecturer's Signature


. Aatural hanquage.
Oesenibiy algo uing human kang ucge. I
tnkutie bul my bo ambigow .

2. Pseudocede
Oecribes algo uring Combntion e notwral

kongage wito programnmingy Censtucl (oiek of coce).


3. oolho
sleps .
Olagyamaie repsexnlaton cusng symaola to depicl
Jeqvence Provicles visual unestanding bal
Imay belem lompex tor lompiealed alyo

4
Pegrniy kanguago
Jpeaiting decy wsng a progranmig bang
Jav, C ... dhs is wnambiquos & prec/ R bil less
intutie or nol eay to undereland

Asymphtic nalycis.
Js a melhod to elescnbe the behavioww clgo (Olen
ehin

tne Inpal Srze grous touomcb inynity & pro vidlo a way
to evauot io etticrercy by foniny en performance.
helps to ompou diftpereñl odgo bard on tme & Siace

lonplerity

. Asymthhc
Mothemaical
Notatiens.

forl to represtnl tamu & spuce Compeaily


....02... Date :
Page No.

Basl Cas.(o)
Repnescnls miaimun time o& spnce fengteety uquie d by
algo oith all possible nputs.. Nh an tdeal titualioscohene.

algo fioiskes ik aciutien as eardy os peaible Represcled

otla Omega (2) notation


Average ec (e)
Shis s epected tina o spoce requned by clg for
Piadam inpat Srze n) and prouides aone ealshe alqoithns
o typlcal Stenaries, RepIeATL oith Theta Ce)
efficienay

3. klosl lax (o)


Repegnl meu tine or spse segused by algo

aeng all pesihe iaput, pnides goarantee the


ogo eitn take lengew thon tas an YebiabilbA caxensus
Repnescated oith Bg D lo) nalaten

Pertonancc Meaucngl
To undestarsd the qfficiencey algo
to evalak & compal baud on pimang copcc

1.
Refes to the ameznl time an algo taks to
Condeks Sk erecuhisn as aa functien e n (inpal size). Melhas
to measuL Ione Cerplexity:o tounling Openilions

3. Empncal eawemenl
4 Benchmkiag

Roll No. Lecturer's Signature


a Space Conpleity
Refes tooroanl of time Upace an algo es

dininy ik exeution. Jhis includes memony space requiree


by inpws, varia blw.& dsta Shuchne wcd in algo.

MeIhods to meane Spae Complesity : Iied Parl

3.Auriliar Spuce

Recrsi ve algoithns are algothms tlat soloe o

Probkrn y Calliny themselus eith moolifecl sel o, inpab

bottrr recuciny problas dnh Snallw & moe mangeable

Sub-polgiew. dhe analyis typicalLy requires -time a


Space lempleity recvsi se proces

•Steps. (Solieed Guzslions l kasl CPage no :S.t))

I. Jdenliy the Recunence Relation

A ecwnence ulation expreses the Overall time

lomdeity D u cursive alo in Smalw sub - problems


Exomple :
Jer tactornal funetion lfactori al ln),the recunence
ulation is :[7 (n)= Tn-t) + o ()].
Date :
Page No. ......03....

Q. Bac Casc
Cekrmint hase tase 's tint Complesiky. Ba
Cac
hLbess to Instance ga probem, cehtch han be solwed
dvecy letd turtnin casiLon

Cscoballybax lax paido a


Cenlibien taalstops 1ecuriion

to revenl atiaik lorps d ensus program termiallen. so,Ohen

h iput eashes tuL bax casc, the algo getun a speatie


Valoe or lnectly sblue the paklum woithtil futhw tesi
Calle

3. Jole eusscnce ulatien


ol
Solo secussnce elatien & find esall tin.
Cempeity ceussencltiag
cikiog ike Bubstton mtnds
hutatds mutacda

4
Space lempleciy
lensidw te dpace ied by secustien Snck for

lach secussi all


Page No. ...05....... Date

Reusnence Kelatuen br Bianyaroh

Siep 1: To Jdenbity ecunce selatien

tren {h)tclOhere, Tn) buratt tme tempteity

To)L
TlA)
(I
+c
n |)
(oterwise)
Base Case
Recanence Relatibn

where, ns topal size


Ciu Coslait tiome
(ensamel
to fin mid empaistn
or Sinple
TCO/a) s tine to seonch key elemenl in ene Es

the tuoo Sub anay h Size (We)

|Slep Qi jo Sole 9uccarenc sulatien whng Subzlitatien


methed or masks dheomm

Substitatiy Melaud

T(a)-T6)+c0
To)- TA)+L0Subanay
lnd so
, n)
sas Ca), so n à reolaced bye

Subsktule in 0 Andny Sequeree eq equlion to


7n)> T(/2) +C to knouw the equahen ih taic
T) = (a)+c] + T C,
Now subsitue 8)
T(n) T(%)3c
T(2)+3c
Roll No. Lecturer's Signature
4 it Centnued till Knumbes o Steps .
then,

TCo)-T ("/)+ ke.

we gzl tine
klhen ecY6TO ago
> As we

Yenches
knouo,

bax ccse &


cemplextly
finally termìnaled ,thl is Ohen

FnyfT) = T(/)
So,let asume Q* = n Then,

- T) + ke [r)-1)
|+kC
I+ Lognc n2* logn - logak

Ten) - l+ logn (e)


(ogn kloga [loga -)
70)- o(Logn) [tlogn() s represnled as Oltogn)
tor time Cermpety
Page No. .....5:........ Date :

Mastors Theorem.

Maske's Theoem cscd hhen tee cgatien


is
is in the formICa) at tfo,
le) kohese]
az| &b>)

To)a n

ula) depends en h (n) & hio = flr

n'0 LABAD

oC)

Ans a

TCo) =n *,un) n, uln)

To)- n'. 0) o lo)

Roll No. Lecturer's Signature


Recumence Reloten o% Binany search wh
Q To).
Soluing
T (o/:)+ c. > Mastes Theorm.
Ans

Logg

n loglu(n)
n°.u (n) u(n) > 7(n) uCn)) a-1)
hn) ftn) c.
nlo9

- (ogn)".c
tleve e is re wntten os (logn). c,ohich i
u evenuallyc

hon) = (togn)°. C

ucn) (logn) * /o1.c [i-o]

. As per u ln) A h ln) Telaten table.

T(o)- o ( ogn)

• tlere loyn.c is Yepres o (togn). )


le- constaat
BASIC OaTA STRUCTURES I

Cperalioas
Oiyoun Set data stralune lao kncon as
Unien Btind) is used to kep tack ef disjanl Subset
cf a patieulan sel. Operstieni l Jndl

Roll No. Lecturer's Signature


Jon Q Subset inlo oa Single Sibsel.

Jind

Oetermine Chich Subsel a pnicalav elemenl y in.


Ihis is scdl to check iy two cleme n cu in Sam Sabsels.

. Drctionaies.
Dis toaries ane absthacl dota types tnal Store

key- vae pais. kach key is unique & used to setieve


Cs50crated 19alie. htso kneen os myps or asoeiati v csaf.

Operalions : I. Insest
J. Search
(Put)
lget)
3. Delek(oemove

(o
Inserl
Adc oa neww key Valwe Poir

2. Seorch
Rehiee Valve asociated wstth given kay

3. Delek
Remove a key- Val pir bascd en ky

yyaph i a cellection noces & edges oheve noces

are Verile d edges aye Conngtlien /o nodes.

.Direted Edges hae drezlion Cone-oay)


a. Undirecled tdges are kordwzelisnel tTwo- wway.
Page No. ...04.. Date :

3. |Aeighicd kdges hau heighls or cosls essOCIald eith therm.

|Unweighkd kdyes hoeno wigits

Cuaph lgoxithns

Breaclth Isal Search (BEs)


Depth insl seonch loEs)
bij kshal dgo
kuskals & Prinl's dlgo

EDUC

dtee a hisaxchtcal dotu Shclne oith neodes

Cenneslud by edqs. has a


Child nedes

almasl
Bnany Thee kach node hes d childreeh lsuft & sight).

K
Biny Seanth Trec
d oioas te ohee te left child ds leo lhan
he poenl neole & the xighl Chilal is gnaler

3. Balancd Thee
Tree ohich maiabins balanced heigh) to ensal
ollogn) operatins.The height o, beft& sight Subbecs
4 any node dtbes by atmisl a Gpecfie talee,ohlen
dor example, AVL tres & Red-black toecs

Roll No. Lecturer's Signature


•Operzliens
t. Onserti en Add oa node to tree Ohle maintoaininy b profales

a. Deletioen Remove a node b reanange to mainlain propzrlies

3. Searching kocal a node wilhin the bec

4. Travesal ist oll nodes in o tree ftn- order, pre- orde

post- o der tor Binony Seorch tres)

. Tree Algoithns.

t.

Q.
Birary Jorch kfieienl
Tee tavesal
emching

Algo (Ike in-orclu, pre-oder &


in Binay Seareh

posl-orcler
tee
tavi
,
3. tleop Sott Wainy binn head to so7t elerenls in oalogn)ioe
Date
Page No.
UNIT: 02.
Oinde d Congueu, Brule orce and Gredy Method

vide ogaupy
an algoi thmy, tohere
opproach to design
preblms
a boken doen unh Soaley Sub
pmobum s
embins
and sole each Sab prlmm becuusilly. heo
Solution to solue tie briginal ppbln

kxample for Divide & Cengues algithns

Gereral Melhod

b.lenbel absthatieD.
C- Merge Sost

dQuick Sosl

e.Brony dach
sSemxch

Generol approach as Oivide & cengues; hd


s diicde, Cengves and Comkne

Algoilhm
DAC (P){ l DAC DiridleAnd Congue Y
/P- Problem, h Piu Smal
SIP)j Hhen it solued dix2clly ceitheil

tuthu dioded it

elkef
diride p inb ale PP Po.

DAc(P,)... DAclP)
apply DA (e.),

Cemin Selutios of PAc (P.). Dnc (a). DAclea)

Roll No. Lecturer's Signature


Birony dearch
in
Divide & Conqvev algor to Seovch key elemenl

a soted omoy

wlaking

1: Stel with & poinks, koo h high, onich porinit ealy poins
.
to beginniny & end of the amey veupeclively.
kowt
& lolin lte mid, mid > high

3. f mid - key, then


key rehn indea o miel.

H mid> key, ten sct high to mid-l & Seoreh the left bod

f mid < keyy then Set loo as micl +| to SeamchAe rig t ho

4. Repal unil s
elenrd is found or amay is exastel.

Algorhrmfor Jherati e binary Seoreh.

BS(on,ony )
igha len lony-l;

ohile (lowe- high){


mid (lovw 4 high)/a.s

( hrn
[mdJ--
(on
re ; mìd
trget) /Elermen found

4 (am Ciaid3 < torget ) (Seoch Regnt ho

tow > mid +l3


Date
Page No.

high mid- j Seoch lefl halh

Teturn -1
So Cempleaty

ahleisl Cax, o liogn)(TtO) T(oD)


b-Arerage Cas, olegn )L
c.Best lass ,o).
|Space Complesity tor ileate RASiON iA oli)

o Recursiwe Mettad
Algoathm ot

RBS (Lib,ky)
4[lazh){

Tehurn ;4

Tehun midi
4Ckey< A(mud]){
rehum Ras ll, mdl, key);
elx
Tehurp RRS (md, h key))

Roll
No Lecturer's Signature
Jime (omplexity is Same as itealive veLon ,

Spute Compety to vecwsie Vevsion is oltogn).

Ovice and onqvev algo to sorl elemenls o omoy

nlakig
a. Pivot Seleel an elenenl as pivot (Iial, kasl, mid o vandm
lemenl)

b Vortiening: Reanange elemenls, Such thal elemnls qreakr than


Pivo t are en ib mght and elenen kesser than pivol re on ft

e. Recuscively Apply Repeat Jom proee securcidy to subonay

by splitiny the anay at dhe pivol

d. lombine now combd all the Subenays to gel a Jorke omoy

Jime Comperity

a. Wosl Casc o (o)(To) T (n-t) +n)


b. Average Cak o nlegn) f7tn): ar (4)+n
C.
Bax Coux o (nlo9n)

Spuce comp lesty

a. wosl Cae o ln)


las o (oyn)
Date
Page No.

kxampla

aLek Pwot () Shil elemsl, Pointkr le)- 2nelemen,aPoiah)


- lasl e lemenl
bPmoves RHS & Stops at elemenl > Pivol

Qmoves lHS & shps at elemenl<= Pivpl.

f P&Q tops and didnt Cross each other oI nol at Same

posifion, then Sap P&Q


d a P& Q stons and Crosed each other o al same poaition, hen
Jasap and Q

V& a ave Suappe d oith eoch


eada othex, & Pivot

elemenl seached at might pos tiorn Now aay s parhhored

|n 2 kalfs aith pivl elemen.

4Repea thu proces wnil al siub amy) oL Seuted tnlley


SorkdSubaneuyfo gel a
Combine all korted
amoy
o + ool

80 qo 45

SO 90
P&Q CrOSsed each other
IS (35) 80 So toosuapQAV

Pivot
Sub ana Sub nad
Roll No. Lecturer's Signature
P P

a ) + oo

P
80) SO (a0)

P
+ o

(G0 so

on qo
Sorted y i s a0

Merge So
Divide i Cenqves olgithrn to sorl amy
Working

a. Divide Splt the anay in a hots has .Ihis duesion

lentinues cntl Cash Subonay lenduirs enly ene clemen,

b. Merge harting tem tet, now lonmpoce a tonšecuhve

Subomays and merqc them, Such thl smotter elemenls


ore ore
plauyee ptaccd in ascending order. Pointers (i.i)
uscd to Cempore elemen ch o Sub reys.

c. At kast all sub amags are merged togelh as


Sor ted oamay
Page No. Date :

Example
6 4 Q L 9 3S
3S

3 s

3 S

Peate i hther sabomayt a Lonpened coit

To Cornpose the elemenb e & Sub amays le e poinks


ibj, LOhese i pounk toiand clenenu o, ene óubanauy

jj poiaks toooads eltmuats q othuw Subarmay

enbaladn
MSa tencept thad hidydetads e ontel

Shutul 4 an algorilbn, Shouong enly high level strchse.

Sa tne Conkat of DAC, lenbel abshalhon poucs a faneLovk


to cmplencnt the melhod

Roll No. Lecturer's Signature


Srady Algtba
Grecdy adgorithm felous local op hrel
Cheicc at each Jtage oth the intnd

epimum.
Ckps (Gymeal Melbod)

G Selecten . Seleal bisl opien bcd Cortain Citerien

at each Stoge

b- Jea siblity.eheck ifb the oeleded eption can be inelueled


in the Solutien ottheut vio lating tostsanti

o. Soutien Repcal untl he solution is Complele

Applca ti ons

a. knapSack problum

b.
O. Job Jeqvencing oHh deadlines
C. Munimum lol spanniny tee
d. Singu Sbwce Shoi kesl poth proble

e. tlutfman (oding , ete.

Gqiven a set 8f lmd, Cach uoilh a weigh! &


Sale. oekrminng the no- op2ag to inclucle in a

lellectien So tnat the total welgt doesnt exceed c


limit & total vale i as karge as pesiilole
Page No. Date :

recdy Aproach

a sot ites baxd on thu ratio oh valoe to wcight (w) e


descendiog order

baat iláns to tu fm dhe wlo


hato ,
addiag

talcing
alen
as much
u as possikall
kaupsack
c! cach
highasl

iam anhl the


knapsacde is full

e Ihu teks
you
eplimaly
Can -laku frichbnal
or the fraclional
pasb oh itm
knpsack problun , Whusd

Goboqusncicg

kxample
ltems 3.
Vaw
weigh

knapsack lapacity la) 20(unght)


temalus)+ ikm3()= 20 weight
Value
>3.SS,

Roll No. Lecturer's Signature


Given a Set o joas ehve each job has n

and a prohit associated ith at t t s lompleked


deddline

geal us to moximi2e the by


by it deadine- Ghe profit

lhin thui ruseelie deadlines.


Scheduliny the jobs

Appoach

a dort jobs in doree decreosing ordr -thi profit

b. Sehedle lach ph ot the Latsl pesaible Sot bcfore ut

deadline thal tree

C. He a data Shattne to kecp tack te Stots.

kxanple

Jobs Je J3 Ju Js . Availeuble slok = 3


probs Duration of cach job - 1 Unit
3 3.
Jobs
deadlline

Consiclered Slot aisi9n | Soluction Proßit

&
Ji
(-2) J
(o-)( J,, Ji

Js (o-)

(o---9 Js,J,J

4-0
Js J,Ji, J

J4 Soutien
Date
Page No.

Minimu Cat pannng te


A Cennecke Subgraph fs oh qraph G(vE)
is caid to be spanning i

a. SShould Cen taún all Verhcex of


b. S'Should Conkun (r-) edgas.

|Main goal to find a Spniag free eilh a maimun Sum


% edgo weighks using krwkals" Bink Alpthns

lkrwkale Algo hye

a. Sot all edges in ascendlug oder th fheis weigha.


b. Add edgs one by ene to MIT Set, ensuriag no Cycle s
is

formed
kaample

Jum 4 edga eighks 2l.

DPgs Algputb

oa.Start oith any verkex qrco the MST by addiag


& the
Somallest edge that Cennects a veitex in the MST to o
Yerkx outside the MST
b.
Make syse no ajele s fermedl

Roll No. Lecturer's Signature


Example
2
2

Sum of edge oeignti : 36.

9Snge cuge Shotsl Pat


te ksl path frn the
aiven
gihen
dousce verkx
T6 ind
to ell
thu
cther
Sho

verhces in the groph .


Approach:
a. Shitialzs the dictlnce to Source os o & to all othw vertic es

inginty

b. Mark all nodes as cnvisiled & set he inibol nede as Cument


node (Source ndde wl be cusnnl node initially )
e. o Cunenl node, lensider oll ik unvisileel neighbors &

Caleulae thein tentative distances threvgh the Cumenl node.


Cempare new distance to cunenl cslance valve & as9n te
Smalle ene

d. Add cmsent node to the scl a isitad nedes. A visitee node


veill net bo chece agpun, his means the shotcsl distance to
the Sowce toom visied nede has been teund
Page No. Date

eSalac ans Unvisited nade uoith the smaleal teatatie


dilance e set t aa new "Cumtnl noce "tuen repect

the prpces fom Skep 3

f. The algo demioas cen all noes hae ban Visied and ad

his poiot,te hasksl poth to eacb node fon Jounce

Kxample

|4

amenl node OeshotiD Visited nodle

14
22 14
7 l;23
L, 2, 3, 6

4 20 ,23,6,4
20

Roll No. Lecturer's Signature


Page No. Date

| Bxkk Eoxe
A Shaight (orunrd arpoadh to Jolue problems by caploig
all possible opians. Smple bud incthecent for large inpats due
to theiu high time Cemplexty Algoithns that follouis baule

oxce appz0ach aei

Alqomtam to tind all occussunces of a pa ltcrn shi0g P

ithin a krt Shing T

Appreach
EOUCAY

Cempare the pattrn h ength m oith tach Subshiog of the eat

e Cenqih n. that shork trn each positino in text.

b-Side Pone Chorackr at a tore over T & Check if the etkrn

matches te suba hiag 41


Jme Cemplexity onxm)
Exampe

APPRD AC
R
|3.

Roll No. Lecturer's Signature


Closet- Pais Probn
ore
Cloct
Alqoithm
to each othw
to
in
tind

a
the
plane
paiw
coith
e
set
poinls

n
thad
polnks .
Appronch

(empite the distane bchecen evony paw 4 ponts & kecp


tack g
thee minimum do lbn founcl.

Example

P- R P- P, Pa- Pi

P, - P3 P3- P
P) - P+ P>- Pa Ps- Pa

Calulate d'stance bchocen e veny paiw &incs closel poi

Smne Conpeity n)
o

Álqoritn to find he Smallest Convex polygen


(Convex hu) tht can encles oll the poinks in the plare

Appocach.

Slont oith the ft mast pont, and find the neñl point
to wrap te set q poinb by mainlainig the Converity

Ime Compeity
or Convex polygen
o cnh) , ohere h u no. poinks in hull.
Date :
Page No.

4 Axlautve Seanc
to eodh through all pesble outiers
Mgonithon
all pemiblu solutiens o a
4 a probum. Used to cvalua

proldam., Thaks It!

Taveliog Jalesgan
Walecman Paoblem
Algorithm to fiod the Shorhesl pesibe roate dhet
visik Cach pouat exacy bnce ke twms o the origlo poiat

Approach

Evaluat all the rautes & tind the ene oith the Sha lest

path utog ezhauthe Jeach

ine Camplexity ol(o), coherenis no.q eithes


Example: Consider four cities: A, B, C, D
with the following distance matrix:
TSP
A B D
A 0 10 15 20
B 10 0 35 25
15 35 0 30
D 20 25 30 0

Using the brute-force method:

•List all permutations of cities starting


from A: e.g., A BD A,
A B DC 4, etc.

• For permutation
A B D ,calculate the
distance: 10 +35 +30 +20 = 9.
• Repeat for all permutations and find the
minimum distance.
PDERAB
CGiven a set og iens,each with a weight b valoe

dekrmiok the no coch uem to incluade in a Collectiem so


hat the otad loeignt is les than br equal to a qiuen amil
and dotal iaueis marimi zed

Approach

Aaluseall posibe lembaationd a ilis & Chose tle one


oith maximun Valwe that fit onthin the ueight lmit

me lomplexity o (a), nà

Roll No. : Lecturer's Signature


Exampe
IHcmsI 2 3
krapsac le (apacity
= Q0
-
weight

ValveD

t elauttls v/w Tato e cll po 5sible item Combination to

Come up oilh the bcsl ne uying ex baustive Seorchin9

I,

13
, Al possible

(I,,I,,Js
(5) (o) (s) = 20.
(ombinal

soln
ipns.
ion)

DAssanreol Proble
Algori thr to minimlza total cost by csigoing

n oorkes to m jobs
jobs.

A proach
kvaluas oll permuttion
possibl job asigomenb &

Choose the éne with -(he minimun Cos t

Jrme tomplexity olo), n s no. jobs,

Example Je
Pi

Peymutati bns J Je J Je
P, P P) P
P P
Al possibe Combina tiont

Pi Ps P

P Pi
Uynamic Programning, Backtackiog ancl Baanch Bano
Page No. Date.
NtT: O3.

Dynamis regragmiag
An apprach to deigo algouithns fo solae

phmketon prokuna by bneaking them deuon into Siplu

avoid Prdundanl anpakatons

Algoritims hal us dynamic Pscqvaziog are i

Gwen a sct o, ikns,each oith a weiqht & value


detemoc the ma vale Ihatcan be chlaind lacy fcleclung
aa Sabsct q utns sch doat tuia bhal zigyt dleæsn nst
xeecl a qien Limit
Approach
OERABA

|Usc a QD
a0 amay DplALA] where iu the ikm idelen k& Wis the
w

oeignt Capacity me Compleaty i) o(n.N)ni no .o} ikms.

Recuyence Relaten:

DPlw] : De[i-Jw] *f1( Ma Yaue uwithaad includhoq im ikem

DP [J[W] = DP [i-J[- w]hen ih iknà tocudeck)


Valt o in ikm t max val of enaniac Capaaty afkY
Inchadicg he fm item.

DP (J[w] =0 khen ilkms i) or weightCapatily lw) = O.


|2m orth weght qreakr than o is nol iacludecl

Roll No. Lecturer's Signature


9 rayeling alesman Pacbern.
Given a Cast cf cihes & tind diztanccs bctuee
shbs ksl posbe voute thal sit Cach
Cach paw, fiod lhe

city ealy
ence & cns to the orign CiHy

Appo ach
approuch tb represent
Uscs a bmask oynamnic programminy

Semt c visied cihes .

3 Al pals Shtal Rath


Jhnd the Shosesl pestns bctween all pais ob
nodes in a weign ted graph

Approach.

a. alyoitlm ib uscol
krzriulluy loyd- liarshull
b. Vec o mahia DJS1, ohere Depre <nts the Sho kst

palh trem nodle i to j.

C. Vpdot thw matrix by lonsidenog eaeh node asan inkme


olicte pont. ataime.

d One a noce is uxd as inkr meciale nocle, it can be uxd


8s inkrmediotte noce thoughoul -ie prores

Ome lempleity u oln)


Page No. Date

Ophaal Biaany Seanco tree


Gjuen a sct & dheinacces prpb poba
|bility onshal a BsT coith min Serch cosl

Appaada

Uc a mabix otlül to_ Stone tle minimum Cosl o,


h the
bioany Scarch hee containing keys fhem to j.

Sme Comdeaity is o la)


Spaa Conpen

GReliablky Desgo
Desigo a bystan wih max sclablity wnng
Cemponents oth qign scliablithy valts al
len shaink.

Approach

Ug Dynanie Preguanming to empul the maimun Yell abilly.

Dekine DP lill cs tne max seliaailty each cemponen ?


Loithin budgel i.

im bspae Cemplaily vomes dupcvrzlarg en the spciie

Roll No. Lecturer's Signature


Backtrackng
Apprcacth or algo techrngue for Jolung problams
by ineremerntelly buldig delutios & abandlening thot
that donl Saishy he ppotiris cens hants.

a. At ench sej? decide on a Chorae fom et % ophcns.


eniwing it decsnt blolate any (onsthainti.

b. Check i cunenl laton mcts prcblems veguirerñenls. not


undo choice & ty nol ophep:

2 Reusie Back toacking


ecssion to explee each pessibu ophen
trern a kt ef optiens.

Approach.

a
O Jor each choice ,apply tie choice & vecunsively
Call

-lu funtien
ead to a ralid so lutien
ecsive Call doesnt
b Jt the
choiu& back tack.
en undo he

B)Jlevotie Backtrocking
Backtracking algorilton that avoidb we g teursio
ecwio
sing an erplieit stack instead
Page No. Date

Appraca.

a.
a Usog erpbat ack to kaup bak of steale kach Skale or

paxhal Jolutino s pusbed coben ik baiog aplared popped


off cohcn backhackog

b.hen a sfat leads to tnvalid soluten the algo


back taacks by popping the Shalk clb the Slect & xploviog
othew altematves.

C larahve backfalabg typically ciscsa loop to Conhol the


|Seorchpund epeatedy processes Stakes unbl all possibilihes
hae ben aoled ora soluetin
found

4Qusen Problenm
dlgonthn to place queens en a Checsbard
Such hat no two queens atack each other.

Approach

Place oa queen in the lSnenl TOwj CnsuL dozsot


queen
Shone Saml Column 20) BY diagnenal oith ano heu quecn

b MoYe to next gow peal

a quecn leads toa Cooglucl emove it & hy

Time olo)
enplexihy
(omplexiby ne no. 0 queens

Spale lomplaity oln)


Roll No. Lecturer's Signature
S tlamil tonian yde
A yle in a graph hat visits cach verkx crally

ence and aetums to dhu Shonliny verkx

Appro ach

Beqin trom a Verkx S add it to the path.


b. Recursl vely add Vories to the path. and enswe the
path templeks a yele.
C. f no Valid pafn w tound ,hen Yemo e the vertcx

try te nežl (Back rack)

Jime Complexity o (n!), n no. verhces .


f Spaa Complexitey o (n)

Ihvoles selechng itns coith given waights

Valus to maxi me thu total al withoal acecclng the

Cayaaty

Apprcach
aloesnt
a.Jnelucle items ene by cne & iy 4e totel weig ht

exteed the Capacity


)Cortinve t
2cceds,then backtack
try tue nl iem,
b. 14 it eeeeds,
tne oith max
C. cuY 4 muwltiple solutien,chocsc hu

profit or vale
Page No. Date :

Ime Complexi ty ola,ns noh itcms.

Spaa Compeny o ln)

Branch And Bound


BB 3 a genoal alganthrn tor ndng tphanotl.

doltiens by systamahcaly lxploung all posi ble &oluctTná


heugh brandhiog(Generaleubprnhens) and prunes
Sabophal solutim using budhng tancteo ohich Cannot
be ltr than the cuset beit soluton

Boundiog
Boundiaq unctiens aN wsed to eshah best possibl
Scution. H thi bound is oorsc thanythe best ercnt
Jouten, the Sub hee à pruned. (or eqval to) or else
bound solution is ieplaed oith Cueal bsl eluhon

Oper bound
or miainka h on problea, an upper bound s an cshma -

kd maximum Valik oh the soldion,(aciordiag b Cumen


bcsl eluben) So that it Could be se ploced bith nienl silaton.

Lower bound
For maximiRaton mabuni, oe louer beund is a eshonated
minimuals
Loith cwhent bc soedo

Types os branch & bound methods

keast Cost ke)

Roll No. Lecturer's Signature


e krap Sack
TO maximize t-volvc oitbin given ight Capaity

eas Cost Ba B
kC BB aluoays cxplones the least- ost node fa.
Nodw at kepl 9 a miorily qvee baxd on thiw cosl. Jhe
Dkn leads to more
tbi cuznl pruning Since les promi eig
nods ae s ikely to be erploxd

Time o (a")

Spaa
Cemplexity

(ornplenly
is ,
sHl erpenenlal bal managad.

2B&B
In FlFO B&B, nodes
nodes ae
are exploed in t he oroler

tly ane generatl


generatael uing a
wsing que. t doesnt netesarily

nedes fisl chich migh t lead


Cplore the mosl pmom gtng

to les tierenl pruring

Iime (enplexity o(a^)

Syue lompleity kxponnlial.


Page No. Date :

Ollknapack Doblermkc)

A node ot level i sepCEent incusion o7 CxcaioO Ob

b Valcs ol ikms are converkd iolo nega tve Sioce hc is wscd to

miomum valwe So luuhorn, but hen


When -- mioimum va
Loluten is Convey kcd back to te we qel besl posible
Soluten with highesl vae eilhun weight Capezity

Use the upper bound to maximum cshmaed Vle so


I the boud is worsytaen it pruned or else t
(or etse egual to uninl bezl soluion)

Lele heplace bound solutien itn Cuneal bal solaztin

d. Stut with an tmpy knapsack and generale naces


by eithan incuding o excluding the nt iken

e. Updote bes stion it a node


a node ogha
ohher a beter feaslale
Soatoo

Tme lampaity ola)

Roll No. Lecturer's Signature :


Pyoblerm. (FIFO BsB
/0 knapsac k

a-Stort with an empty qvev to stre nodes

b. nodas will cen tain :


kevel (rdex o ikem)
Weight (7otad weight upto tnls posrit)

vae tl
o va upto ts point

Bourd (Upper bound) o

s. Jnd bound yal (Max vawe that can he obtoained). by


ikms unhl the knapsack s full if the item
ncluding

doesnt fit . incuele aa trach tn e it to til the knapsack

txactly (ter kiner elanahe)


d. Engvevc initial node Leved - o, weight o,valve -o

6. lhile qvee iw nol emply


. Dequeve node & generati next level nodes tom trs node
I. One iocude te nert ikm.
2. on Cxcudes the next item.
. 1e
f souton is betrer then updlotta or else enqve e

nooleit holds pem) ge for a bette solitio

f. Process Coninves untl the


Coninves untl the quee cmpty

Time (omplexiy o o)

Space lomplerity o)
Page No. Date
UNIT:- 04 Graphs Trees

Graph Taaessal
Jho aelos visiing hocls of groph is a sylmae
ManneN do Cxplee the graph

t hal une orConnezluity

techniquesi
. & galhi
primony graph travtal
ngormalin abeal

DRS cxple as fer as pesile along


cs cach branch

before kackthacking. 4is inpeweakd using stack or


ecssi metheds

Steps

a. tanl n Sousce node, mavk it es vistked push it to the


Stack

b-it an aceccrt Hede wnusiked node, nask it as itiked &


psh orn to the Stack.

c 4 no adjecern unvisited node it is feundke pop the node


om the Statk.

d. Regpal this uilil te Sack i enp'y.

BAS Crplaes the graph lecl ky deel, statng


trom fue sowce varla & Cxplovinq all ia nelghbos befove
en to mel leol Inplemienkeel Laing queit
Roll No. Lecturer's Signature iN!
Steps

verta,mnl t as enqueve visilecl &

Cngvev it.

b. ØNouw enqvee its al adiceenl unvisi ted nodes &mank


them es it.(lode at tral position) ,And
visited. Ihen degvee
Simply degve ue node f hot'
to t has no adiecend unvis)ted nodes
C. Repeal tiu oitn eveny fist node un the queve.

r4sr

Jaansitivo one
clo

#s a tonsst in gaph tteony thal vofes lo

. It is TCpre senlkd by reachabi tity


sRchability voslices

Tmatiz T where i

7C:JtG)- 1tt thre bapath trom volex? lo vsrlexj

Fttt ao evengvertx is veathatte trom-itsetf

Metnods to fnds tantihve cosue : t. Joyd -otyertty


2 DFS
Page No. Date :

a.Joitilz mabix T with nxn dimentiens

CJoy lach baw el Ci,j) Cach Pater mi clhalo vesk t

d. Jome spaa Cempleily e


Aoyd-lOarshall algo u
qien by on)& olo) spectly

a gnitial3e an nxn natrix t L9ith al eoes Sct toO

or Cach
b. verkx in the graph perform DES Stortiag
facm Sousce ver tex

eMark each erkx Teachahe foum a ponlcnla lerka

Iime lemmplnly olnCnte)) (es no.f edges)


Space tompeaky o tn)

Roll No. : Lecturer's Signature


d qaph dhat is diuctel and Centains ne
me cyeles. In
suoch any wtex fen
frem nottu
a

Wtex
DAG,
-tveyh
ids persibe to

a diched gooph ,
hl the s no
to

eniqinal ertex,thus no Gples aisl.


Cbme hmck to

•Topoegiçal Orderding
ordeing onties in a te DAG Such
d linear

-thal yor euy dEled edge u, vertex u cemes

bfone vertex v in ordering

Steps

1. Compue ench En degree no.e, nceming edges foo cach e

2. Delele sedex eith un degre= 0. & add it to the

topological ordaving

3.Repeal these Steps unlil all vertices are

topolcgical orderig
Vsl, usl,T-l
•Indegree y R&R>0, Q2,S=l,
Q -D,Sz Va usT=l
P& R verhtes delekd, tndaree

•Q deleled,inderee S= V: O & u= T-l

.S&Y deleled indegee , u=T=0


.udT delelecl.
7opolcgical Crdering :pR QsvuT
Page No. Date

Taies
AH like data staaluse usd Storiosal

Sfigs & invete


a taee-

sttrievol of

asecialid coith dhings.


keys . hue
for

kya aL Lnaley

am lompeaty is oln), ehau m

Jypa

Basta fou o tics

b.kach node vepesnb alemmen prefik ane shigs


c-kach cdge spresas a charatka
Path frm hel - lo represenb a lompelc shig in bie.

kxamplei
S- bear, hel, blds buls ack, Sfop

C P
k)

Roll No. Lecturer's Signature


Taie
tie and ee
Space optiized veson endovd
add a new nede enly ehen boanching
a Nodes coith a Sunge chb e toith tiew chld,
mesgcd
trus lompesaing trie.

6. Roch edg Can vepetnl dequen a

a cingle oracer

deurdh & intkartien Compaly is olm).

Sto
id u) C

Shardard tie Cempesed tie

H's a Speeia lized type & tie -thal aoe dll he


a gien darg twing a Compresed hee.
Suttres

a- kath node repreznls a sqfie ta ching. & all Sufirs


insesttd into the taie
Date :
Page No.

Kxample

mlze
Lmize
nimize
tnimize
Minimlze
EDUCA

m
Suffia -be

Roll No. Lecturer's Signature


charcth agne Sndang.

Searh tndlcngine indexing

a Standard tries sfores Aonge Cecabdany for fosl Cok up b

g Loords, Whch fundamental is tor indexny


tnserling

uhie viny data tawcd on Cokzl.

6. Compesed dies ephixt mem woger cspeclaly ohen indexing

krge lorpuss text hee many o them Jhme lomman


Jrefixes.

C. sutox tries are benefetal or handeling Ast prebiens


ALloted to Jubstings in a kext ao we kneo the
tet dacunenl in a subfi x hee is nol a colleelier oord

eul ratw a corl inioy sting letes ,tus no sepoale


coords

. Exlernal Seonchng

Ohu refers to algoathn & dstastuelwes digned

to handlle kange data kt -d dernt fit entively


unto mem,

disb.
ypically stoet al

ohe main goa is to minict no. csk octes by oictoly


mañginy dsta ehievul inselon Oporalions
Page No. Date :

B- Trecs
loith eell
spaihe type g sef- balancig tee
defined prper hes, Codaly iscd tor managing harge
datasds etficanly on disk.

Propzzlics

B-hee Of order m hos nodes lhal Can Conleigs.


no chileden betusecrn m/a and m Also no y
Claildren no - block pooksPoiohiag touwonds Childien)

Each node has a key and a acodrd poiakr, cohere

key is the cenkenl & seord peink points dak

no cz gecord poioks) Bnd (no.H keuys = nD - childrn- 1)

c- A leaps are al same depth, ensunng the te Temans


balanced

Dzevatiens

Soonca deanh daka kascd en kayt eith ologo) Ceomplenl.

6-Saserlien Shsed nodea wnile balanciaq tee koith olegn) lonpta

e. Delehen Remo nods aeanangenods


h tomaintain B- Trce

ooperties toth o(iegn) Coplexity

Roll No. Lecturer's Signature


• A, BTrees
Thesc ore gencralizatun ch B- 7recs. Dhey ne pwamele

Yizd by too tnicgess A 4 B lohich o'efines -the tenslvounts

bn the he
te stucte

Tioperlies

a The no keys n
in each noode ranges fro Ala to B,
enaing
the taee emous balenced .
b kach nede con hav bctween A& B ehildren

c. The tee semains balancedl, ll leaves aLal dame oleptt.

Operatons

Seavch, Srsestion, Oelction oith o (togn) tomplexity.

ehere n s
n is no.
no keys dn
Und: os. Cempalalietl lemdary S Forallel clgpilams
Page No. Date

Nondsleseinste allbo NP
lgo thal Can maku mtlipla chorca al eath.
Step for ib nal oclieo.so we cant preditl the D/P

titn H e knouo the inptt. Unlike delamiaishe algo,


Chich folloLas a Sioge & predtelable poth.

Same input uel giedbenl cutpal forcferedl Ianda


execufien. Jhús we Sollien, no
accuale Solations : we jel enly approk

Redurts.
Censide decigon Trobams P & Pe

P
P. with
with
Onpal
Japal
(I)
(I)
algo la1) het
alGolA)Ohane Aa
, AI
is knoLên
unkneeo

lenverled nto

94 P. lan be Jold uing Aa, then Ii i) reploced sorth


Ta to find the solatieo uriogy a funeloo

P, s Teducible to Pa

I,l)=IoAlgoalhm
A

Jolustion for P

Aprden ith capuit either YES or No w Salo to

be decisn prcblem

Roll No. Lecturer's Signature


NP -tlord
malolem b NP-tard t every prtblem in nP
A

vuduced unng polynomial- time retalor


Can be polyoeniotly

A.B. C NP roblums

oll these can be uced to x. ohen ts called


4

NP hard .
. NP-Ceyplel
A prelblem th u both in ND A NP- hord s

knoen as NP Com plele

NP
HHord

NP Cempleke

Poly nomial Jimu


o
a clas q algllns
Polynemiod time algothnis are

time Compsily lan be expmescl ao a


ehee the poynomiol

e inpat). kike on),ollogn).


Page No. Date

Watisfablity Dobjen
SAY Standh tor Beoleon salatiability
podun. Dchiaifi ent Gi a Boolearn expiesion
expesien wiay vaiables kogical h operaliens ika AND.
OR, NO7), the SAT problem csks uhelhw these

leml asignmunl q appropricala alocs Ae orfalse)to


le liablu trol male te enhre epresion evalueb
do tue

Example
Boolean Expresni
{s thexe an assignnnen] tah alcA ttrat to Z, ysz
thd maks Ahis gomla tuei

assiannt

Mmultipl meessers tokung hitutaneesly fo alr ia

cach onich am be hlied anependanlhy & Concuisoly

Pros

|Signfcarlly rluca onpalolondint by duidling pnbum.

|Hardle Aamgu dalaink fyoanly by uing mutala precesod

Roll No. Lecturer's Signature


Maximize utilleation e att aailabtu hordwan,impong
Bnall tieieney.

syatms

Medds for paralid lompaing.

PRAM
PRAM ands tor parallel senclon occss machune

nedl ehich s an absact medel Lucd to design &

analyee ponollel olgoilhms

ceniids c muttiph pyetesses thl Shere Cemmon me)


Cach pecesor (an
eah ncccs any mem
Upucu, LOhee cell
ohet

Simuttareeuly aud al pecesors m &yncherizl wsng


a Commen clock

Vaiants.

a EREW{kx cluoine rcad kxclusie wwite)

No e po ce ss o1S Con ead frm or ouk to toe Same


Tnem cell Smultaneously
b CREW (Cenewsenl Read Kxcui oale)

Multipu proeesos ean reod fren Same mem cell Sinutaneoudy


bud enl Can wnte ol u time
eny
c CReW (toncwant Reac Cenusonl it

Mutiple precesod Can ead tren & onte to e came mem


Date :
Page No.

Procesas Mi amCnopd
amcngd in a d

dicly itb us
procesoó lem Can lemmunioal erly

mahix ultiplicaticn onaje preSig

3Smple Porallel ind and lenque


Dredun inb
Similas
dub problm
n Siuztune to
s
dlncleel

solwrel
e ovigul probum Shen toch
secuiiely ln pasallel ancl
.
snallew Sub- prtlglems

menged quikly cnce dhe panalld secus


EDUD
Call etun

essing en Srall subsat m the prlolun k Hhem apply paralel


algo defiaish soliag the pnsm Sn sanu insarc
benn bcqentiol posl precesicg nede to be dore on each
Subel afk pornlel algonthn onpleks

( Recusit Doybung
he main idea is o saz eilh small subsels&
erathly lembing thum an pas chll he Lohele prtldn

dwde - anel-tenquv elleus top -deuon achnigue

A can be duciabed hy Lit Ranking prdm Ponald


plix peblun

Roll No. Lecturer's Signature


hee
lemplek binawy
A toee ohich hew cll lls
(emplelely falled orh nodcs btepl the loal enefluel.

Last lved mal be illed trom lf to ight

Morgng dolkd lists


k
Cempleke binmy
To mergc
heé . steps
sorted

:
ists
theiery usirg a

a Dlace each Wt al a leae nede.

o Koch inenal noole Gtores the mnged eutt of icts chalchen.

d. Cenhne wil he al Stores e

Ihu method veducs tine lemplexity to olntog k), where


hn is total no-cf elemen acYoFS oall dists.

Othes Operatens that Cen be conmpukd using lemplele

buoy
Soked lhsk
Merginy
Porald pelix Sum(an)
3. lend Operations

4 Balanced erch Opevali ens.


G.
t Rome Qery & updlate operaliens.

You might also like