Data Structure and Algorithm
Data Structure and Algorithm
eveh
tuo slrinys:
fongest common
nerrssaniy
alnng
11.1
aubsequence:
n
The Longest
s of iengih n, and sfnng
a conttguous
iength
Comman
Subsoquonce (LCS) pmblem is as follous.
goal I
fo
We are
prtdue he
the fongrst seguenr oJ eharuclers thal aPIar lejt-ta-nghi (bul not
S= ABAZOC
T= BACBAD
In this rase. the LCS hns kength and is ABAD. Aother way lo kmk at il is we are indings
the striug
n l-I malehing belwTYTI Ome ol llie ktleTN in S and mine al the letteTs in T soch 1hal none al the
in the malehing ONS Ceh other.
gew
in geniomies: givei twa DNA fragnients,
For inxtanee, this prollrm eonw up all the tin
typ" of
the 1.c3 BiVes Inorihul Mi ntsont wlunt tiay havt iu eaON1 Ala
be Way tu iri up. e ne
we will kok at
now molve tlhe lCS problem Ning Dynurnie Prugrnnming. AN ulbprubens
Lat
le LCS of
a prefix of and a pretix
wrry inl alboul huling the íengih ol
S of T: nunning
the s
ad vT we pairs
thrt
ol rehs
all
ean noity the nkgorithn r lo proxlice
Cano 1i if si] # TG]? Thwn, the desirecd mabmeqtienee has uo igore one of Sp| or TbI so
wlhat
- 1.j1. LES{3. j
1Cs.j] = ar(LCS| -1).
Cae 2: what il
St)= TDI' Then the 1.CS of S[1..i d T|l.J] might as well malcth 1hem up.
ir tananee, you conlti alwinys nteh it ta Tul lanteul. S0, 1 Lhls Ce we nve
- -1
LCS|j| =l+LCSji 1.j
So, w ean jusl do lux loops (ovvrT values of andl j) , tilling in lhe LCS vesing thee rules. Here's
i
it looksi like pietarinlly
lor the exampe nbev, wh S nlong hr kltinat culuui anl
T alon
wlhat
the top rew.
BA
** CB** A D
Just ll aut Lhis Matrix rUw liy row, doing coHNAnt Amaunt ol wrk per vatry, 0
ths takes
"Tha anwwer (the cif tlhe Les otS and T) H un the lower-rnght
({rora) time overnll. final length
dynamic programming
techniques
Therefore'"Dynamic programming is a
1. Knapsack problem.
2. Chain matrix multiplication.
5. Tower of hanoi.
6. Checker Board.
7.Fibonacci Sequence.
8. Assembly line scheduling.
Dyname Programming is otten uscd im optimization problenis (A problen with many possihle
solutons lor which we Want to an optimal solution
tind
Dynamic P'rogramming works when a problem has the following two main properties.
Overlapping Subproblcms
Optinal Subsinucture
A
Not to be confused with Hash list or Hash tree.
from.
koy_1
koy_2 Hash
0 valuo_1
valuo_2
Function
valuo
koy 3 valuo4
(1,20)
(2,70)
(42,80))
(4,25)
a
(12,44)
(14,32)
a (17,11)
hash table kn a direct file
file organisation.
R5 SV4HD
<b>Hash Filerganizatien</b
in DBMS
hash function
A hash function is any function that can be
used to map data of arbitrary size to fixed-size
hash
keys function hashes
John Smith
01
Lisa Smith 02
03
p4
Sam Doe
05
Sandra Dee
12 Dee".
Hash functions and their associated hash
length keys
collision).
Hash functions are related to (and often
confused with) checksums, check digits,
bukel at h(k)=0
=
buckelat (k)
bucket at h{k) =2
buckel ot h{k)
=3|
KEY: dato
burkeetH4)-4
eA pounfer
chaining
.Through chaining,insertion in a
hash table always occurs in O1)
since linked lists allow insertion
in constant time.
combinatorial optimization,important in
N
Solution of a travelling salesman
generalizationsof TSP
have been added. Sometimes two or more edges may have the same cost. The order in
the are chosen, in Different MSTs may result,
which edges this case, does not matter.
but they wllall have the same total cOst, which will always be the minimum cost.
13
VP Cllpe f Fngirrin t Winue
Algorithm:
The algorithm for finding the MST, using the Kruskal's method as follows:
is
Algorithm Kruskal (E, cost, n, t)
E G has n the
IS the set of edges in G. [u,v]
is
vertices. cost
ne Th fin
cost returned.
e Set
o edges in the minimum-cost spanning tree.
/
is
fina
u
0mincost 0.0
while
n -1) and (heap not empty)) do
K hen
t[, 1] =u t[,
mincost:mincost+
2]:=
cost [u, V];
v
Unlon (d.
K)
Running time:
The number of finds at most 2e, and the number of unians at most n-1.
is
for a the algorithm has a
ncluding the initiall zation time the trees, this part
compexity that is Just slightl y more than o (n+e).
We can add at most n-1 edges to tree T. So, the total time for operations on T is
Ofn).
25
Example
5
5
1:
0a3
14
GVP Cullege of
Engileering lr
Wuei
I
placed
is earned. The is to the
objective that maximizes the
ill knapsack earmed. total profit
K
,
chosen to
Since
the
knapsack capacity
be at most 'm. The problem
Is
is
m, weas:
stated
require the tatal wetght of all objects
maximize
P
1
Algorithm
w then the
tnejetsare aieeybeen sortednto non-increasing order of D
r to n
do x[)
:= D.0 # initiallze x
r 1
to n do
if
x
w)> U then
[
break;
0 U-wi
1,0;
if
(is n) then xil := u/wil;
Running time:
he objecs are
to easi
be sorted into non-decredsing order of
W pi
ratio. But ir we
asreg time to sort tne oujects, the algoritnrn requires
initially ornly
on)urme
Example
Consider the tollowing Instance of theknapsack problerm: n =3, m= 20, (Pi P2, P)
(25,24, 15) and (w, W3 W) (16, 15, 10). =
1. First, we try to till the knapsack by selecting the objects In some order:
2 1/3 | 1/4 18x 1/2 + 15 x/3 +10 x 1/4 25 x 1/2 +24x1/3 +15 x 1/4 =
2.
the object with the maxiun pron t
Select
PI
X1X2X PiA
2/31 15x2/3+ 10x1 =20 24 x 2/3 + 15 xI =31
in or
Sort the objects order
oi
thenon-increasing order te ratlo pi/ X Select the
units ofspace is left. select the object with next largest p./ x.ratlo, so x= and the
profit eamed is 7.5.
- 20
/2|15x1+ 10
x 1/2
24x1+15x 1/2 -31.5
This solution is the optimal solution.
Dijkstra's Minimal Spanning Tree
Algorithm
The
4.8.7. Single Source Problem: DDKSTRA'SALGORITHS
Shortest- Path
thepreousiy
the lengths of
studied grapls,
its edges
tthe edge labels re called as COsls, but here e thin
i lstras
Dijkstra' s algorithm
ag 5 sirlar
takes a labeledto
prirs
graph
alort of dig
for,
and a pair verticesinina spair trs
P and 9, and inds the
2
1
peati
O
O0-0{9 Shortest Patlis
AIgorihm
talse Intislkre
ani
io -tont w,
Pul
SIvIrue, lst[v
v
in
o Tea td lul+ OM w) then Upuuale dislances
dist[ disl [ucost [u,w
unning ume:
Depends an implementation af data structures lar dist.
Buld
a stncture wneieen
at most m =E
times deC Te se the va lue of an item m
times select the sma lest value
n
*
Or array A OnJ B01C0 = O (log
which
gves O (n totd
For
hean
tota.
A
=0 tn}; 8 =O (log nj;C n) which gives o (n +m log n)
EXampie
6
1
Solution:
0 3 6
30 2 4
6 2 0 14
The cost adjacency matrix is 4 10 2
42 0 2
Status[v be either 0', meaning that the shortest path from v to vo has
will
Dist[v] will be a number, representing the length of the shortest path from v to
Vo found so far.
vext[v] will be the first vertex on the way to Vo along the shortest path found so
far from v to vo