Anda di halaman 1dari 15

GettingStartedwiththeSportofProgramming

Thisdocumentistoguidethosepeoplewhowanttogetstartedwithcompetitiveprogramming.
Theonlyprerequisiteisthatyouknowbasicsofatleastoneprogramminglanguage.This
documentwasinitiallymadeforfreshersatIITKanpur.Soitmaycontainphraseslikediscuss,
discussedetckindlyignorethem.

Hopethisdocumentwillhelpyou.

Note:Pleasenotethatthisdocisnotmeanttoexplainconceptsindetails.TheAimof
thisblogistoguideyouaboutwhichtopicsyoushouldreadandpracticeinasystematic
way.However,inmanyplacesshortexplanationshavebeenincludedfortheir
relevance.Relevantproblemsaregivenaftereachtopic.Propersourcesaregivenfrom
wheretheseconceptscanbestudied.Wheresourcesarenotmentioned,thatmeans
theseareveryverypopularandyoucangettoknowaboutthemjustbyasinglegoogle
search.Moveforwardandenjoyit!

Ifyouhaveanyqueries/suggestions,pleasecontactus:
AbhilashKumar
abhilak@iitk.ac.in
https://www.facebook.com/abhilash.276

TriveniMahatha
triveni@iitk.ac.in
https://www.facebook.com/triveni.mahatha

Coordinators@ProgrammingclubIITKanpur[201415]
https://www.facebook.com/groups/pclubiitk/

Allthefollowingthingsarefromourexperiencenotsomethingwrittenonstone.

Youwillneedtoshowmotivation.
Languagesthatshouldbeused
C/C++/JAVA(yourchoice)
WewillfocusonC++,JAVAisslow(onebigadvantageofJAVAisBigIntegers,
wewillseelater)
C++islikesupersetofCwithsomeadditionaltools.So,basicallyifyouhave
knowledgeofC,youarereadytocodeinC++aswell.Otherwisegobackand
learnhowtowritecodesinC/C++.
SometimesknowledgeofPYTHONishelpfulwhenyoureallyneedbigintegers.
PARTICIPATEPARTICIPATEPARTICIPATE(theonlymantra)
SPOJ:ItsaproblemArchive(recommendedforallbeginners)
Startwithproblemshavingmaximumsubmissions.Solvefirstfewproblems
(maybe20).Buildsomeconfidence.Thenstartfollowingsomegoodcoders
(checktheirinitialsubmissions).Thenstartsolvingproblemstopicwise.
Nevergetstuckfortoolongintheinitialperiod.Googleoutyourdoubtsandtryto
sortthemoutoryoucandiscusswithsomeone(ONLYINTHEBEGINNING).
Beforegettingintolivecontestslikecodeforcesorcodechef,makesurethatyou
havesolvedabout5070problemsonSPOJ.
CODECHEF:Doallthethreecontestseverymonth.DoparticipateinCodeChef
LunchTimeforsure.
Evenifyouareunabletosolveaproblemdoalwayslookattheeditorialsandthen
codeitandgetitaccepted(thisisthewayyouwilllearn).
Andevenifyouareabletodoit,dolookatthecodesofsomegoodcoders.See
howtheyhaveimplemented.Againyouwilllearn.
SamepointapplytoTopCoderandCodeforcesaswell.
Codeforces:4to5shortcontestsof2hourinamonth(Dothemonceyoudevelopsome
confidence).
TopCoder:Onceyouhaveproperexperienceandyoucanwritecodesveryfast.

OnlineProgrammingContests
Youwritecodesandsubmitthemonline.Thejudgerunsyourcodeandcheckstheoutputof
yourprogramforseveralinputsandgivestheresultbasedonyourprogramsoutputs.Youmust
followexactI/Oformats.Forexample,donotprintstatementslike:pleaseenteranumber,etc
:P

Eachproblemhasconstraints:
Properlyanalysetheconstraintsbeforeyoustartcoding.
TimeLimitinseconds(givesyouaninsightofwhatistheorderofsolutionitexpects)>
orderanalysis(discussedlater).
Theconstraintsoninput(veryimp):Mostofthetimeyoucancorrectlyguesstheorder
ofthesolutionbyanalysingtheinputconstraintsandtimelimit.
MemoryLimit(Youneednotbotherunlessyouareusinginsanelylargeamountof
memory).

Typesoferrorsyoumayencounterapartfromwronganswer:
RunTimeError(MostEncountered)
Segmentationfault(accessinganillegalmemoryaddress)
Youdeclaredarrayofsmallersizethanrequiredoryouaretryingto
accessnegativeindices.
DeclarationofanarrayofHUGEHUGE(morethan10^8ints)size_.
DividingbyZero/Takingmodulowithzero:O.
USEgdb(willlearnincominglectures)
Compilationerror
YouneedtolearnhowtocodeinC++.
USEGNUG++compilerorIDEONE(becarefultomakecodesprivate).
TimeLimitExceeded
Youprogramfailedtogeneratealloutputwithingiventimelimit.
InputFilesarenotrandomlygenerated,theyaremadesuchthatwrongcode
doesnotpass.
Alwaysthinkofworstcasesbeforeyoustartcoding.AlwaystrytoavoidTLE.
Sometimesalittleoptimizationsarerequiredandsometimesyoureallyneeda
totallynewandefficientalgorithm(thisyouwilllearnwithtime).
Sowheneveryouareindoubtthatyourcodewillpassornot.Mostofthetimeit
wontpass.
Againdoproperorderanalysisofyoursolution.

Sometimeswhenyouarestuck.Checktherunningtimeofotheracceptedcodestotakean
insightlikewhatOrderofsolutionotherpeoplearewriting/whatamountofmemorytheyare
using.

4MB~arrayofsize10^6.Or2darrayofsize10^3*10^3
StandardMemorylimitsareofOrderof256MB.

Orderanalysis:
Orderofaprogramisafunctiondependentonthealgorithmyoucode.Wewontgointheoretical
detailsjustthinkOrderofprogramasthetotalnumberofstepsthatprogramwilltaketogenerate
outputgenerallyafunctionbasedoninputlikeO(n^2)O(n)O(logn).

SupposeyouwriteaprogramtoaddNnumbers.Seethefollowingcode.

intcurr,sum=0
for(inti=0i<ni++)
{
scanf(%d,&curr)
sum=sum+curr
}

Totalnumberofcomputations=n*(1+1+1+1)
ntimescheckingi<n.
ntimesi++
ntimesscanf
ntimes+operating

Sototalof4*N.
WeremovetheconstantandcallitO(N)
ThisisthesimplestIcanexplain.Youwillgetfurtherunderstandingwithpracticeandlearning.

Youmustknowrunningtimeofthesealgorithms(MUST)
BinarySearch>?
Merge/Quicksort>?
Searchinganelementinsorted/unsortedarray>?
HCF/LCM/Factorization/PrimeCHeck?

Weallknowthecomputationpowerofaprocessorisalsolimited.
Assume1sec~10^8operationspersecond.(forspojoldserveritis4*10^6).
Keepthisinmindwhilesolvinganyproblem.

IfyourprogramtakesO(n^2)stepsandproblemshasTtestcases.ThentotalorderisT*N^2.

ForT<100andN<1000.Itwillpass.
ButforT<1000andN<1000itwont.
NeitherforT<10andN<10000.

INTOVERFLOW:
Sumthreenumbers.
Constraints:
0<a,b,c<10^9
intmain()
{
inta,b,c
scanf(%d%d%d,&a,&b,&c)
intans=a+b+c
printf(%d,ans)
return0
}

Thisprogramwon'tgivecorrectoutputforallcasesas3*10^9cannotbestoredinINTSyou
needlonglongintorunsignedint(4*10^9).
whatif0<a,b,c<10^1000?

ComparingDoubles:
intmain()
{
floata
scanf(%f,&a)
if(a==10)printf(YES)
return0
}
float/doubledonthaveinfiniteprecision.BEWARE(6/15digitprecisionforthemrespectively)
Letsdothefollowingproblem.
http://www.spoj.com/problems/GAMES/(discussed)

StandardTemplateLibrary(STL):
Inyourcodesometimesyouneedsomedatastructuresandsomefunctionswhichareused
quitefrequently.Theyalreadyhavelotsofstandardfunctionsanddatastructuresimplemented
withinitselfwhichwecanusedirectly.
DataStructures(Tobediscussedinlaterlectures)
Vectors
Stack
Queue
Map
Set
Functions
Sort
Reverse
GCD
Swap
permutation
binarysearch(left+right)
max,min
pow,powl(findoutthedifference)
memset

Nowimaginewritingcodesusingtheseinbuiltfunctionsanddatastructures.Itwouldbemuch
moresimplernow.

Whatheaders/librariesshouldyouinclude?
Basicallytheabovefunctions/DSareindifferentlibrariesSoinsomecasesyoumayneedto
includemanyheaders.Butyoucanincludeeverythingusingjustoneheader.

#include<bits/stdc++.h>

Trythefollowingproblem:
www.codechef.com/problems/ANUUND

Whichoftheaboveinbuiltfunctiondidyouuse?

WhatifwehavetosortanArrayofstructure?
Youcaneithermakeastructandwritecomparefunctionforit.(Readmoreatcplusplus.com)
Oryoucanuseanvectorofpair
ReadThis:
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=sorting

Nowyouarereadytostartcompetitiveprogramming.
Youcancontinuereadingthisdocorgetstartedonyourown.Goodluck:)

First, you must learn the basic and well known algorithms . Not only algorithm but you must
also understand why that works , proof , code it and analyze it . To know what basic
algorithms you must know you can read here .
http://www.quora.com/Algorithms/What-is-needed-to-become-good-algorithmist-like-top-ra
nkers-in-Topcoder-Spoj-GCJ
http://www.quora.com/Algorithms/What-are-the-10-algorithms-one-must-know-in-order-to-
solve-most-algorithm-challenges-puzzles
http://www.quora.com/Computer-Science/What-are-the-10-must-know-algorithms-and-data
-structures-for-a-software-engineer

Also read these answers on how to start competitive programming and get good at it.
http://www.quora.com/ACM-ICPC-1/For-an-ACM-beginner-how-should-I-start
http://www.quora.com/Can-I-crack-the-ACM-ICPC-in-1-5-years-if-I-have-to-start-from-scr
atch
http://www.quora.com/Competitive-Programming/What-was-Anudeep-Nekkantis-Competitive
-Programming-strategy-to-become-35th-in-Global-ranking-in-just-6-7-months

Topcoder has very nice tutorials on some topics here
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=alg_index.
You must also read this book topic wise to understand an algorithm in more broader way
http://ldc.usb.ve/~xiomara/ci2525/ALG_3rd.pdf.

To get good at writing fast codes and improving your implementation
follow this:
My personal advice is to start practicing on topcoder . Start with Div2 250 master it then
start with Div2 500 master it then move to Div1 250 .Also read the editorials of problem you
solve and the codes of fastest submissions to learn how to implement codes in simple and
elegant way.Meanwhile keep learning algorithms and keep practicing them on SPOJ or
Codechef or Codeforces . And do read the tutorials, after a time you will realize that the
tricks and methods to solve are repeating themselves . We learn from practice only . If you
read same thing 5 times in different tutorials then it will not be stored in your short term
memory only right .

Belowarefewtopicstostartwithandproblemsrelatedtothosetopic.
Theyareverybasicstuffsandyoucanlearnallyouneedtoknowbyjustgoogling.
WheniwillgetsometimeIwilltrytoupdateandgivemoredetailsaboutthetopicsa
newbieshouldcover.
Trytodoalltheproblemsstatedbelowifyouareabeginner.
IMPORTANTNOTE:WehadalreadytakenfewlecturesonDP(DynamicProgramming)soyou
willfindnothingaboutDPinthisarticle.ButallbeginnersareadvisedtosolvefewsimpleDP
problemsalso(Iwillpostlatermostprobablyby22nd).Youcanstartwithtopcodertutorialon
DP.

PRIMES
PrimeCheck(O(logn)alsopossiblereadaboutmillerrabbin)
Factorization
Numberoffactors
Sumoffactors
GeneratingPrimesusingsieveoferatosthenes
BoundsonnumberofprimestillN
Eulerstotientfunction
PracticeProblems:
http://www.spoj.com/problems/NDIV/
http://codeforces.com/problemset/problem/431/B
http://www.spoj.com/problems/GAMES/
http://www.spoj.com/problems/GCJ101BB/
http://www.spoj.com/problems/GCJ1C09A/
http://www.spoj.com/problems/MAIN72/
http://www.spoj.com/problems/WINDVANE/
http://www.spoj.com/problems/NDIV/
http://www.spoj.com/problems/PTIME/
http://www.spoj.com/problems/NDIVPHI/
http://www.spoj.com/problems/NOSQ/
http://www.spoj.com/problems/AFS/
http://www.codechef.com/MAY13/problems/WITMATH/
http://www.spoj.com/problems/CUBEFR/

Tryasmanyasyoucan.
Otherthingsthatyoucanreadmeanwhile
EulerTotientfunctionandEuler'stheorem[[READ]]
Modulofunctionanditsproperties
MillerRabinAlgorithm [[READ]]
ExtendedEuclid'sAlgorithm [[READ]]
KeepexploringSTL
ProverunningtimeofHCFisO(logn)
Trysortingofstructures
PracticefewproblemsonseveralOnlineJudges
Trytodo+*operationsonlargenumbers(<1000digits)usingchararray
(forlearningimplementation)
Numberoffactorsandsumoffactorsinsqrt(n)time,Numberofprimestill
N

Gothroughthesetutorials(Thelistedproblemsmightbetoughbutdoreadthetutorial)
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=primalityTesting
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=combinatorics
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=math_for_topcoders
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=primeNumbers

BasicNumberTheory
ModulooperationsandInversemodulo
Howtocomputea^b%pinO(logb),wherepisprime
FindNthfibonaccinumbermodulop[ReadMatrixexponential]
n!%p(whatifwehavelotsoftestcases)
ETF(calculation/calculationusingsieve)
Eulertheorem,Fermatslittletheorem,Wilsontheorem [[READ]]
nCr%p(inversemodulo)(readaboutextendedeuclidalgorithm)
(p1)!%pforprimep,UseoffermattheoreminMillerRabin(Probabilistic)(
millerrabin.appspot.com)
64Choose32<10^19wecanprecomputetillhereina2dimensionalarray[Learnuseof
therecursiverelation:(n+1)Cr=nCr+nC(r1)]
Numberofwaystotraversein2Dmatrix[CatalanNumber](whatifsomeplacesare
blocked?Hint:DP)
a^b%c.GivenHcf(a,c)=1.AndwhatifHcf(a,c)!=1.[[READChineseRemainder
Theorem,notusedmuchincompetition]]
MatrixExponentiation
solvinglinearrecurrenceusingmatrixexponentiation(likefibonacci)

Practiceproblems:
http://www.spoj.com/problems/DCEPC11B
http://www.codechef.com/MAY13/problems/FTRIP/
http://www.spoj.com/problems/FIBOSUM/
http://www.spoj.com/problems/POWPOW/
http://www.spoj.com/problems/POWPOW2[[CRT]]

PowerofBITS
Numbersarestoredasbinarybitsinthememorysobitsmanipulationarealway
faster.
Bitwiseoroperator:|
Bitwiseandoperator:&
Bitwisexoroperator:^
Bitwiseleftshift:<<
Bitwiserightshift:>>
Memsetanditsusesusingfunction:sizeof()
BitmaskanduseofBitmaskinDynamicProgramming[[subsetDP]]
SomecoolTricks
n=n*2::n=n<<1
n=n/2::n=n>>1
checkingifnispowerof2(1,2,4,8)::checking!(n&(1n))
ifxismaxpowerof2dividingn,thenx=(n&n)
Totalnumberofbitswhicharesetinn=__builtin_popcount(n)
settingxthbitofn::n|=(1<<x)
checkingifxthbitofnisset::checkingifn&(1<<x)isnonzero
Problem:YouaregivenNnumbersandanumbersS.Checkifthereexistsome
subsetofthegivennumberswhichsumsequaltoS.Whatifyouareaskedto
computethenumberofsuchsubsets?
Practice:
http://www.spoj.com/problems/SPCO/
http://codeforces.com/problemset/problem/114/B
Morewillbeaddedlater

Readthisforfurtherknowledge
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=bitManipulation

BinarySearch:
Trythis:http://codeforces.com/problemset/problem/431/D
Understandtheconceptofbinarysearch.Bothleft_binary_searchand
right_binary_search.Trytoimplementitonyourown.Lookatothersimplementation.
sampleimplementation:
intl=0,r=10000,key_val=SOME_VALUE,m
while(rl>1)
{
m=(l+r)>>1
intval=some_non_decreasing_function(m)
if(val<key_val)l=m
elser=m
}
if(some_non_decreasing_function(l)==key_val)returnl
elsereturnr

//thiscanbemodifiedinavarietyofways,asrequiredintheproblem

PracticeProblems:
http://www.spoj.com/problems/AGGRCOW/
http://codeforces.com/problemset/problem/431/D[[Learntsomethingnew?]]
http://www.spoj.com/problems/PIE/
http://www.spoj.com/problems/TETRA/
http://www.spoj.com/problems/KOPC12A/

TheBeautyofStandardTemplateLibraryofC++
Vectorsinonedimensionandtwodimension
http://www.codechef.com/MAY14/problems/CHEFBM

solve:http://www.codechef.com/MAY14/problems/COMPILER
Nowusestackstotasteitsbeautyandsolvethefollowingproblemtoo.
http://codeforces.com/problemset/problem/344/D

Queue
http://www.spoj.com/problems/DONALDO/
PriorityQueue
http://codeforces.com/gym/100247/problem/I[[FirsttrywithoutusingPriority
queue]]

Set
http://www.spoj.com/problems/FACEFRND/[[Firsttrywithoutusingset]]
WhatifItellyouthatapartfromscanningtheinputthisproblemcanbe
donein2lines?Interesting?Think!

Map
http://www.codechef.com/MARCH13/problems/TOTR/
http://codeforces.com/gym/100247/problem/C

SomePracticeProblemsBeforeyouproceedfurther

http://www.spoj.com/problems/DCEPC11B/
http://www.spoj.com/problems/AGGRCOW/
http://www.codechef.com/problems/CHEFBM
http://www.codechef.com/JUNE13/problems/PERMUTE
http://www.spoj.com/problems/KOPC12A/(recommended)
http://www.codechef.com/MAY13/problems/WITMATH/(recommended)
http://codeforces.com/problemset/problem/431/D(recommended)
http://www.spoj.com/problems/SPCO/
http://www.spoj.com/problems/FIBOSUM/
http://www.spoj.com/problems/POWPOW/(recommended)
http://www.codechef.com/AUG13/problems/CNTSOLS/
http://www.spoj.com/problems/IOPC_14F/
http://www.spoj.com/problems/NDIVPHI/(recommended)
http://www.spoj.com/problems/AU12/(easy)
http://www.spoj.com/problems/ETF/(easy)
http://codeforces.com/problemset/problem/114/B(easy)
http://www.spoj.com/problems/HISTOGRA/[[Hint:usestacks]]
http://www.spoj.com/problems/HOMO/
http://www.spoj.com/problems/NGM2/

GRAPHS
Trythefollowingproblems:
PrimePath
PrayatnaPR
AnyIdeas?

Def:Thinkgraphsasarelationbetweennode,relatednodesareconnectedviaedge.

Howtostoreagraph?(spacecomplexity)
AdjacencyMatrix(usefulindensegraph)using2Darrayofbool/ints.
AdjacencyList(usefulinsparsegraph)O(min(deg(v),deg(u)))usingvectorof
ints.

YoumustknowthefollowingterminologiesregardingGraphs:
Neighbours
Node
Edge
Degreeofvertices
DirectedGraph
ConnectedGraph
UndirectedGraph
Connectedcomponents
ArticulationPoints
ArticulationBridges
Tree[[connectedgraphwithNnodesandN1edges]]
Leaves
Children
Parent
Ancestor
RootedTree
BinaryTree
KaryTree
Cycleingraph
Path
Walk
DirectedAcyclicGraph[[DAG]]
TopologicalSorting(Notveryimportant,inmyopinion)
BipartiteGraph(TreeisanexampleofBipartiteGraph.InterestingIsntit.)

BreadthFirstSearch/Traversal(BFS)[[veryimportant,masteritassoonaspossible]]
Application:Shortestpathinunweightedgraphs

DepthFirstSearch/Traversal(DFS)[[veryveryimportant,masteritassoonaspossible]]
Infinitelymanyapplications,justkidding:P(ButItstrue,Indeed!)
Nowtrytheproblemsgivenatthebeginning!
PracticeProblems:
http://www.codechef.com/JUNE14/problems/DIGJUMP
http://www.spoj.com/problems/PRATA/
http://www.spoj.com/problems/ONEZERO/
http://www.spoj.com/problems/PPATH/
http://www.spoj.com/problems/PARADOX/
http://www.spoj.com/problems/HERDING/
http://www.spoj.com/problems/PT07Z/
http://www.spoj.com/problems/NICEBTRE/
http://www.spoj.com/problems/CERC07K/
http://www.spoj.com/problems/BUGLIFE/
http://www.spoj.com/problems/COMCB/
http://www.spoj.com/problems/NAKANJ/
http://www.codechef.com/IOPC2013/problems/IOPC13N/
http://www.codechef.com/IOPC2013/problems/IOPC13G/
http://www.codechef.com/IOPC2013/problems/IOPC13C

Problem:YouaregivenaGraph.FindthenumberofconnectedcomponentsintheGraph.
Hint:DFSorBFS.

Problem:Youaregivenagridwithfewcellsblockedandothersopen.Youaregivenacell,call
issource,andanothercell,callitdest.Youcanmovefromsomecellutosomeanothercellv
ifcellvisopenanditisadjacenttocellu.Youhavetofindtheshortestpathfromsourceto
dest.
Hint:TrytothinkthegridasaGraphandapplysomeshortestpathalgorithm.Whichone?You
think!

Problem:YouaregivenaTree.Youneedtofindtwoverticesuandvsuchthatdistance
betweenthemmaximum.
Hint:TrytodoitinO(1)numberofDFSorBFS!


YetToBeAdded
GreedyAlgorithms
generallyrealisationbased
usuallyinvolvesortingortakingmax/min
theyaresometimeseasybutdifficulttoprove
mostoftimewhengreedyfailsitsDP(realisationviaknapsackfractionalvs0/1)
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=greedyAlg

DPproblems

MaximumSumSubarray
FindingNCR
Matrixfilledwithnumbersfindmaximumvaluepathfromupperleftcornertolowerleftcorner
Tougherproblemonsameconcept
LCS
AmediumlevelproblemwhichusesLCS
IOPCLCSproblemtorealisethatitcanbedoneinO(N)memory
KNAPSACK
LIS(AlsopossibleinO(nlogn))
CoinChange
MatrixExponentionincoinchange(harejumpcodechef)
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=dynProg

introductiontocompetitiveprogrammingStanford

Anda mungkin juga menyukai