Sei sulla pagina 1di 6

26/4/2015

CountpossiblewaystoconstructbuildingsGeeksforGeeks

GeeksforGeeks
Acomputerscienceportalforgeeks

GeeksQuiz
Home
Algorithms
DS
GATE
InterviewCorner
Q&A
C
C++
Java
Books
Contribute
AskaQ
About
Array
BitMagic
C/C++
Articles
GFacts
LinkedList
MCQ
Misc
Output
String
Tree
Graph

Countpossiblewaystoconstructbuildings
Givenaninputnumberofsectionsandeachsectionhas2plotsoneithersidesoftheroad.Findall
possiblewaystoconstructbuildingsintheplotssuchthatthereisaspacebetweenany2buildings.
Example:
N=1
Output=4
Placeabuildingononeside.
Placeabuildingonotherside
Donotplaceanybuilding.
Placeabuildingonbothsides.
N=3
http://www.geeksforgeeks.org/countpossiblewaystoconstructbuildings/

1/6

26/4/2015

CountpossiblewaystoconstructbuildingsGeeksforGeeks

Output=25
3sections,whichmeanspossiblewaysforonesideare
BSS,BSB,SSS,SBS,SSBwhereBrepresentsabuilding
andSrepresentsanemptyspace
Totalpossiblewaysare25,becauseawaytoplaceon
onesidecancorrespondtoanyof5waysonotherside.
N=4
Output=64

Westronglyrecommendtominimizeyourbrowserandtrythisyourselffirst
Wecansimplifytheproblemtofirstcalculateforonesideonly.Ifweknowtheresultforoneside,we
canalwaysdosquareoftheresultandgetresultfortwosides.
Anewbuildingcanbeplacedonasectionifsectionjustbeforeithasspace.Aspacecanbeplaced
anywhere(itdoesntmatterwhethertheprevioussectionhasabuildingornot).
LetcountB(i)becountofpossiblewayswithisections
endingwithaspace.
countS(i)becountofpossiblewayswithisections
endingwithabuilding.
//Aspacecanbeaddedafterabuildingorafteraspace.
countS(N)=countB(N1)+countS(N1)
//Abuildingcanonlybeaddedafteraspace.
countB[N]=countS(N1)
//Resultforonesideissumoftheabovetwocounts.
result1(N)=countS(N)+countB(N)
//Resultfortwosidesissquareofresult1(N)
result2(N)=result1(N)*result1(N)

BelowisC++implementationofaboveidea.
//C++programtocountallpossiblewaytoconstructbuildings
#include<iostream>
usingnamespacestd;

//ReturnscountofpossiblewaysforNsections
intcountWays(intN)
{
//Basecase
if(N==1)
return4;//2foronesideand4fortwosides

//countBiscountofwayswithabuildingattheend
//countSiscountofwayswithaspaceattheend
//prev_countBandprev_countSarepreviousvaluesof
//countBandcountSrespectively.

//InitializecountBandcountSforoneside
intcountB=1,countS=1,prev_countB,prev_countS;

http://www.geeksforgeeks.org/countpossiblewaystoconstructbuildings/

2/6

26/4/2015

CountpossiblewaystoconstructbuildingsGeeksforGeeks

//Usetheaboverecursiveformulaforcalculating
//countBandcountSusingpreviousvalues
for(inti=2;i<=N;i++)
{
prev_countB=countB;
prev_countS=countS;

countS=prev_countB+prev_countS;
countB=prev_countS;
}

//Resultforonesideissumofwaysendingwithbuilding
//andendingwithspace
intresult=countS+countB;

//Resultfor2sidesissquareofresultforoneside
return(result*result);
}

//Driverprogram
intmain()
{
intN=3;
cout<<"Countofwaysfor"<<N
<<"sectionsis"<<countWays(N);
return0;
}
Output:
25

Timecomplexity:O(N)
AuxiliarySpace:O(1)
AlgorithmicParadigm:DynamicProgramming
OptimizedSolution:
Notethattheabovesolutioncanbefurtheroptimized.Ifwetakecloserlookattheresults,fordifferent
values,wecannoticethattheresultsfortwosidesaresquaresofFibonacciNumbers.
N=1,result=4[resultforoneside=2]
N=2,result=9[resultforoneside=3]
N=3,result=25[resultforoneside=5]
N=4,result=64[resultforoneside=8]
N=5,result=169[resultforoneside=13]
.
.
Ingeneral,wecansay
result(N)=fib(N+2)2
http://www.geeksforgeeks.org/countpossiblewaystoconstructbuildings/

3/6

26/4/2015

CountpossiblewaystoconstructbuildingsGeeksforGeeks

fib(N)isafunctionthatreturnsN'th
FibonacciNumber.

Therefore,wecanuseO(LogN)implementationofFibonacciNumberstofindnumberofwaysin
O(logN)time.
ThisarticleiscontributedbyGOPINATH.Pleasewritecommentsifyoufindanythingincorrect,oryou
wanttosharemoreinformationaboutthetopicdiscussedabove

RelatedTopics:
BuildLowestNumberbyRemovingndigitsfromagivennumber
SetCoverProblem|Set1(GreedyApproximateAlgorithm)
Findnumberofdaysbetweentwogivendates
HowtoprintmaximumnumberofAsusinggivenfourkeys
WriteaniterativeO(Logy)functionforpow(x,y)
VisaInterviewExperience|Set6(OnCampus)
Countnumberofwaystoreachagivenscoreinagame
GreedyAlgorithmforEgyptianFraction
Tags:DynamicProgramming
1
Tweet 2

Writingcodeincomment?Pleaseuseideone.comandsharethelinkhere.
Megusta

0Comments
Recommend

GeeksforGeeks

Share

Login

SortbyBest

Startthediscussion

Bethefirsttocomment.

Subscribe

AddDisqustoyoursite

http://www.geeksforgeeks.org/countpossiblewaystoconstructbuildings/

Privacy

4/6

26/4/2015

CountpossiblewaystoconstructbuildingsGeeksforGeeks

GeeksforGeeks
Like Youlikethis.

Youand96,409otherslikeGeeksforGeeks.

Facebooksocialplugin

InterviewExperiences
AdvancedDataStructures
DynamicProgramming
GreedyAlgorithms
Backtracking
PatternSearching
Divide&Conquer
MathematicalAlgorithms
Recursion
GeometricAlgorithms

PopularPosts
Allpermutationsofagivenstring
MemoryLayoutofCPrograms
UnderstandingexternkeywordinC
Medianoftwosortedarrays
Treetraversalwithoutrecursionandwithoutstack!
StructureMemberAlignment,PaddingandDataPacking
IntersectionpointoftwoLinkedLists
LowestCommonAncestorinaBST.
CheckifabinarytreeisBSTornot
SortedLinkedListtoBalancedBST
Follow@GeeksforGeeks

Subscribe

RecentComments
shashiraj
program1compileswithoutanyerror,but...
Doescompilercreatedefaultconstructorwhenwewriteourown?0minutesago
Websub
I'mjustwonderinghowtomodifythiscodein...
http://www.geeksforgeeks.org/countpossiblewaystoconstructbuildings/

5/6

26/4/2015

CountpossiblewaystoconstructbuildingsGeeksforGeeks

LargestSumContiguousSubarray17minutesago
Prateek
staticvoidprintParentheses(Strings,intn,...
Printallcombinationsofbalancedparentheses57minutesago
AndyToh
Mycompiletimesolution,whoseoutputagrees...
GreedyAlgorithms|Set2(KruskalsMinimumSpanningTreeAlgorithm)2hoursago
TinkerBell
Goodone!Onesuggestionthough:Pleasetake...
NthnodefromtheendofaLinkedList4hoursago
Twinkle
Reallyverynice
DivideandConquer|Set4(StrassensMatrixMultiplication)4hoursago

@geeksforgeeks,SomerightsreservedContactUs!
PoweredbyWordPress&MooTools,customizedbygeeksforgeeksteam

http://www.geeksforgeeks.org/countpossiblewaystoconstructbuildings/

6/6

Potrebbero piacerti anche