Professional Documents
Culture Documents
n
n
k
n
k
n
n
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
dynamicprogramming.
Aim: Write a program to find shortest path for multistage graph using
dynamicprogramming.
Theory:
Definition:multistagegraphG(V,E)
Adirectedgraphinwhichtheverticesarepartitionedintok2disjointsetsVi,
1ik
If<u,v>E,thenuViandvVi+1forsomeI,1i<k
|V1|=|Vk|=1,ands(source)V1andt(sink)Vk
c(i,j)=costofedge<i,j>
Findaminimumcostpathfromstot
Figure9.1(5stagegraph)
ThevertexsinV
1
iscalledthesourcethevertextinV
K
iscalledthesink.Gisusually
assumedtobeaweightedgraph.Thecostofapathfromnodevtonodewissumofthe
costsof edges in the path. The "multistage graph problem" is to find the minimum cost
pathfromstot.EachsetV
i
iscalledastageinthegraph.
Manyproblemscanbeformulatedasmultistagegraphproblem
Anexample:resourceallocationproblem
nunitsofresourcearetobeallocatedtorprojects
N(i,j)=netprofitwhenjunitsofresourceallocatedtoprojecti
V(i,j) = vertex representing the state in which a total of j units have
alreadybeenallocatedtoprojects1,2,..,i1
Programto findshortestpathformultistagegraph using
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
DPformulation
Everystotpathistheresultofasequenceofk2decisions
Theprincipleofoptimalityholds(Why?)
p(i,j)=aminimumcostpathfromvertexjinVitovertext
cost(i,j)=costofpathp(i,j)
cost(k1,j)=c(j,t)if<j,t> E,otherwise
Thencomputingcost(k2,j)forallj Vk2
Thencomputingcost(k3,j)forallj Vk3
Finallycomputingcost(1,s)
Tofindtheshortestpath of multistagegraph showninfigure9.1.
Stage5
cost(5,12)=0.0
Stage4
cost(4,9)=min{4+cost(5,12)}=4
cost(4,10)=min{2+cost(5,12)}=2
cost(4,11)=min{5+cost(5,12)}=5
Stage3
cost(3,6)=min{6+cost(4,9),5+cost(4,10)}=7
cost(3,7)=min{4+cost(4,9),3+cost(4,10)}=5
cost(3,8)=min{5+cost(4,10),6+cost(4,11)}=7
Stage2
cost(2,2)=min{4+cost(3,6),2+cost(3,7),1+cost(3,8)}=7
cost(2,3)=min{2+cost(3,6),7+cost(3,7)}=9
cost(2,4)=min{11+cost(3,8)}=18
cost(2,5)=min{11+cost(3,7),8+cost(3,8)}=15
Stage1
cost(1,1) = min {9+cost(2,2), 7+cost(2,3), 3+cost(2,4),
2+cost(2,5)}=16
Recordingthepath
d(i,j) = value of l (l is a vertex) that minimizes c(j,l)+cost(i+1,l) in
equation(5.5)
InFigure9.1
d(3,6)=10d(3,7)=10d(3,8)=10
d(2,2)=7d(2,3)=6d(2,4)=8d(2,5)=8
)} , 1 ( cos ) , ( { min ) , ( cos
,
1
l i t l j c j i t
E l j
V l
i
+ + =
> <
+
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
d(1,1)=2
Whenlettingtheminimumcostpath1,v2,v3,,vk1,t,
v2=d(1,1)=2
v3=d(2,d(1,1))=7
v4=d(3,d(2,d(1,1)))=d(3,7)=10
Sothesolution(minimumcostpath)is1 2 7 10 12
anditscostis16
Algorithm /ProgramSnippets:
Voidmultistage(graphG,intk,intn,intp[] )
//TheinputisakstagegraphG=(V,E)withnverticesindexedinorder
//ofstages.Eisasetofedgesandc[i][j]isthecostof<i,j>.
//p[1:k]isaminimumcostpath.
{
floatcost[MAXSIZE]intd[MAXSIZE],r
cost[n]=0.0
for(intj=n1j>=1j){//Computecost[j].
letrbeavertexsuchthat<j,r>isanedge
ofGandc[j][r]+cost[r]isminimum
cost[j]=c[j][r]+cost[r]
d[j]=r
}
//Findaminimumcostpath.
p[1]=1p[k]=n
for(j=2j<=k1j++)p[j]=d[p[j1]]
}
Conclusion:
Timecomplexity
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
method.
Aim: Write a program to implement 8queens problem using backtrack
method.
Theory:
Backtracking is kind of solving a problem by trial and error. However, it is a well
organizedtrialanderror.Wemakesurethatwenevertrythesamethingtwice.Wealso
make sure that if the problem is finite we will eventually try all possibilities (assuming
thereisenoughcomputingpowertotryall possibilities).
Generalmethod
Usefultechniqueforoptimizingsearchundersomeconstraints
Express the desired solution as an ntuple (x1, . . . , xn) where each xi 2 Si, Si
beingafiniteset
Thesolutionisbasedonfindingoneormorevectorsthatmaximize,minimize,or
satisfyacriterionfunctionP(x1,...,xn)
Sortinganarraya[n]
Findanntuplewheretheelementxiistheindexofith smallestelementina
Criterionfunctionisgivenbya[xi]_a[xi+1]for1_i<n
SetSiisafinitesetofintegersintherange[1,n]
Bruteforceapproach
LetthesizeofsetSibemi
Therearem=m1m2mnntuplesthatsatisfythecriterionfunctionP
In brute force algorithm, you have to form all the m ntuples to determine the
optimalsolutions
Backtrackapproach
Requireslessthanmtrialstodeterminethesolution
Formasolution(partialvector)andcheckateverystepifthishasanychanceof
success
Ifthesolutionatanypointseemsnotpromising,ignoreit
Ifthepartialvector(x1,x2,...,xi)doesnotyieldanoptimalsolution,ignore
mi+1mnpossibletestvectors
evenwithoutlookingatthem
All the solutions require a set of constraints divided into two categories: explicit and
implicitconstraints
Definition1Explicitconstraintsarerulesthatrestricteachxitotakeonvaluesonlyfrom
agivenset.
ExplicitconstraintsdependontheparticularinstanceIofproblembeingsolved
Alltuplesthatsatisfytheexplicitconstraintsdefineapossiblesolutionspacefor
I
Examplesofexplicitconstraints
*x
i
>=0,orallnonnegativerealnumbers
*x
i
={0,1}
*l
i
<=x
i
<=u
i
Definition 2 Implicit constraints are rules that determine which of the tuples in the
solutionspaceofIsatisfythecriterionfunction.
Program to implement8queensproblemusing backtrack
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
Implicitconstraintsdescribethewayinwhichthexismustrelatetoeachother.
Determineproblemsolutionbysystematicallysearchingthesolutionspaceforthegiven
probleminstance
Useatreeorganizationforsolutionspace
8queensproblem
Place eight queens on an 8 8 chessboard so that no queen attacks another
queen
*Identifydatastructurestosolvetheproblem
*Firstpass:Definethechessboardtobean88array
*Secondpass:Sinceeachqueenisinadifferentrow,definethechessboard
solutiontobean8tuple(x1,...,x8), wherexiisthecolumnforithqueen
Identifyexplicitconstraints
*Explicitconstraintsusing8tupleformulationareSi={1,2,3,4,5,6,7,
8},1 <=i<=8
Solutionspaceof8
8
8tuples
Identifyimplicitconstraints
* No two xi can be the same, or all the queens must be in different
columns
Allsolutionsarepermutationsofthe8tuple(1,2,3,4,5,6,7,8)
Reducesthesizeofsolutionspacefrom8
8
to8!tuples
Notwoqueenscanbeonthesamediagonal
Thesolutionaboveisexpressedasan8tupleas4,6,8,2,7,1,3,5
1 2 3 4 5 6 7 8
1 Q
2 Q
3 Q
4 Q
5 Q
6 Q
7 Q
8 Q
Figure10.1(OneSolutionto8queensproblem)
The8QueensProblem:
Givenisachessboard.Achessboardhas8x8 fields.Isitpossibletoplace8queenson
thisboard,sothatnotwoqueenscanattackeachother?
ThenQueensproblem:
Given isa boardofnbynsquares.Is it possible toplacenqueens(thatbehaveexactly
likechessqueens)onthisboard,withouthavinganyoneofthemattackany otherqueen?
1. Anotherexampleofaproblemthatcanbesolvedwith backtracking:
o Place 8 queens on a 8x8 chess board so that no queen attack each other
(findallsolutions)
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
52
ExamplesSolutions:
Figure10.2(Solutionsto8queensproblem)
Algorithm: TheBacktrackingAlgorithmfornQueens
Problem: Position nqueensonachessboardsothatnotwoareinthesamerow,column,
ordiagonal.
Inputs:positiveintegern.
Outputs:allpossiblewaysnqueenscanbeplacedonan nx nchessboardsothatnotwo
queensthreateneachother.Eachoutputconsistsofan arrayofintegerscolindexedfrom
1 ton,wherecol[i] isthecolumnwherethequeenintheithrowisplaced.
ProgramSnippets:
include<stdio.h>
defineTRUE1
defineFALSE0
int*board
intmain()
{
board=(int*)calloc(8+1,sizeof(int))
board++
//heregoestheuserinputnoofqueensdoesntmatterinthiscode
intcol
intqueens=2//examplefromuserinput
for(col=1col<=8col++)
placeQueens(1,col,queens)
}
voidplaceQueens(introw,intcol,intqueens)
{
inti
for(i=1i<rowi++)
{
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net
if((board[i]==col)||((row+col)==(i+board[i]))||((rowcol)==(iboard[i])))
{
check=FALSE
}
else
check=TRUE
}
if(check==TRUE)
{
board[row]=col
if(row==8)
{
for(i=1i<=queensi++)
printf("(%d,%d)",i,board[i])
printf("\n")
}
else
{
for(i=1i<=8i++)
placeQueens(row+1,i)
}
}
}
www.jntuworld.com
www.jntuworld.com
www.jwjobs.net