ebook img

Competitive Programming 4 - Book 2 PDF

352 Pages·2020·8.711 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Competitive Programming 4 - Book 2

This is the 100% identical eBook (PDF) version of CP4 Book 2 that was released on 19 July 2020 Please read https://cpbook.net/errata for the latest known updates to this PDF c Steven,Felix,Suhendry (cid:13) ii Contents Authors’ Profiles vii 5 Mathematics 273 5.1 OverviewandMotivation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 5.2 AdHocMathematicalProblems . . . . . . . . . . . . . . . . . . . . . . . . . 274 5.3 NumberTheory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 5.3.1 PrimeNumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 5.3.2 ProbabilisticPrimeTesting(JavaOnly) . . . . . . . . . . . . . . . . 284 5.3.3 FindingPrimeFactorswithOptimizedTrialDivisions. . . . . . . . . 284 5.3.4 FunctionsInvolvingPrimeFactors . . . . . . . . . . . . . . . . . . . 286 5.3.5 ModifiedSieve. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 5.3.6 GreatestCommonDivisor&LeastCommonMultiple . . . . . . . . . 288 5.3.7 Factorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 5.3.8 WorkingwithPrimeFactors . . . . . . . . . . . . . . . . . . . . . . . 289 5.3.9 ModularArithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 5.3.10 ExtendedEuclideanAlgorithm . . . . . . . . . . . . . . . . . . . . . 292 5.3.11 NumberTheoryinProgrammingContests . . . . . . . . . . . . . . . 293 5.4 Combinatorics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 5.4.1 FibonacciNumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298 5.4.2 BinomialCoefficients . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 5.4.3 CatalanNumbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 5.4.4 CombinatoricsinProgrammingContests . . . . . . . . . . . . . . . . 301 5.5 ProbabilityTheory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 5.6 Cycle-Finding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 5.6.1 ProblemDescription . . . . . . . . . . . . . . . . . . . . . . . . . . . 308 5.6.2 SolutionsusingEfficientDataStructures . . . . . . . . . . . . . . . . 308 5.6.3 Floyd’sCycle-FindingAlgorithm . . . . . . . . . . . . . . . . . . . . 309 5.7 GameTheory(Basic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 5.8 MatrixPower . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315 5.8.1 SomeDefinitionsandSampleUsages . . . . . . . . . . . . . . . . . . 315 5.8.2 EfficientModularPower(Exponentiation) . . . . . . . . . . . . . . . 316 5.8.3 EfficientMatrixModularPower(Exponentiation) . . . . . . . . . . . 317 5.8.4 DPSpeed-upwithMatrixPower . . . . . . . . . . . . . . . . . . . . 318 5.9 SolutiontoNon-StarredExercises . . . . . . . . . . . . . . . . . . . . . . . . 321 5.10 ChapterNotes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 6 String Processing 325 6.1 OverviewandMotivation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 6.2 AdHocString(Harder) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 6.3 StringProcessingwithDP . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 iii CONTENTS c Steven,Felix,Suhendry (cid:13) 6.3.1 StringAlignment(EditDistance) . . . . . . . . . . . . . . . . . . . . 329 6.3.2 LongestCommonSubsequence. . . . . . . . . . . . . . . . . . . . . . 331 6.3.3 NonClassicalStringProcessingwithDP . . . . . . . . . . . . . . . . 331 6.4 StringMatching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 6.4.1 LibrarySolutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 6.4.2 Knuth-Morris-Pratt(KMP)Algorithm . . . . . . . . . . . . . . . . . 333 6.4.3 StringMatchingina2DGrid . . . . . . . . . . . . . . . . . . . . . . 336 6.5 SuffixTrie/Tree/Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338 6.5.1 SuffixTrieandApplications . . . . . . . . . . . . . . . . . . . . . . . 338 6.5.2 SuffixTree. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 6.5.3 ApplicationsofSuffixTree . . . . . . . . . . . . . . . . . . . . . . . . 341 6.5.4 SuffixArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343 6.5.5 ApplicationsofSuffixArray . . . . . . . . . . . . . . . . . . . . . . . 351 6.6 StringMatchingwithHashing . . . . . . . . . . . . . . . . . . . . . . . . . . 355 6.6.1 HashingaString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 6.6.2 RollingHash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 6.6.3 Rabin-KarpStringMatchingAlgorithm. . . . . . . . . . . . . . . . . 357 6.6.4 CollisionsProbability . . . . . . . . . . . . . . . . . . . . . . . . . . . 358 6.7 AnagramandPalindrome . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 6.7.1 Anagram. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 6.7.2 Palindrome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359 6.8 SolutiontoNon-StarredExercises . . . . . . . . . . . . . . . . . . . . . . . . 363 6.9 ChapterNotes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364 7 (Computational) Geometry 365 7.1 OverviewandMotivation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365 7.2 BasicGeometryObjectswithLibraries . . . . . . . . . . . . . . . . . . . . . 368 7.2.1 0DObjects: Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368 7.2.2 1DObjects: Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371 7.2.3 2DObjects: Circles . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376 7.2.4 2DObjects: Triangles . . . . . . . . . . . . . . . . . . . . . . . . . . 378 7.2.5 2DObjects: Quadrilaterals. . . . . . . . . . . . . . . . . . . . . . . . 381 7.3 AlgorithmsonPolygonwithLibraries . . . . . . . . . . . . . . . . . . . . . . 384 7.3.1 PolygonRepresentation . . . . . . . . . . . . . . . . . . . . . . . . . 384 7.3.2 PerimeterofaPolygon . . . . . . . . . . . . . . . . . . . . . . . . . . 384 7.3.3 AreaofaPolygon. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 7.3.4 CheckingifaPolygonisConvex . . . . . . . . . . . . . . . . . . . . . 386 7.3.5 CheckingifaPointisInsideaPolygon . . . . . . . . . . . . . . . . . 387 7.3.6 CuttingPolygonwithaStraightLine . . . . . . . . . . . . . . . . . . 388 7.3.7 FindingtheConvexHullofaSetofPoints . . . . . . . . . . . . . . . 390 7.4 3DGeometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396 7.5 SolutiontoNon-StarredExercises . . . . . . . . . . . . . . . . . . . . . . . . 398 7.6 ChapterNotes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400 8 More Advanced Topics 401 8.1 OverviewandMotivation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401 8.2 MoreAdvancedSearchTechniques . . . . . . . . . . . . . . . . . . . . . . . 402 8.2.1 BacktrackingwithBitmask . . . . . . . . . . . . . . . . . . . . . . . 402 8.2.2 State-SpaceSearchwithBFSorDijkstra’s . . . . . . . . . . . . . . . 405 8.2.3 MeetintheMiddle . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407 iv CONTENTS c Steven,Felix,Suhendry (cid:13) 8.3 MoreAdvancedDPTechniques . . . . . . . . . . . . . . . . . . . . . . . . . 411 8.3.1 DPwithBitmask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411 8.3.2 CompilationofCommon(DP)Parameters . . . . . . . . . . . . . . . 412 8.3.3 HandlingNegativeParameterValueswithOffset. . . . . . . . . . . . 412 8.3.4 MLE/TLE?UseBetterStateRepresentation. . . . . . . . . . . . . . 414 8.3.5 MLE/TLE?DropOneParameter,RecoverItfromOthers . . . . . . 415 8.3.6 MultipleTestCases? NoMemoTableRe-initializations . . . . . . . . 416 8.3.7 MLE?UsebBSTorHashTableasMemoTable . . . . . . . . . . . . 417 8.3.8 TLE?UseBinarySearchTransitionSpeedup. . . . . . . . . . . . . . 417 8.3.9 OtherDPTechniques. . . . . . . . . . . . . . . . . . . . . . . . . . . 418 8.4 NetworkFlow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 8.4.1 OverviewandMotivation . . . . . . . . . . . . . . . . . . . . . . . . 420 8.4.2 Ford-FulkersonMethod. . . . . . . . . . . . . . . . . . . . . . . . . . 420 8.4.3 Edmonds-KarpAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . 422 8.4.4 Dinic’sAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423 8.4.5 FlowGraphModeling-Classic . . . . . . . . . . . . . . . . . . . . . 428 8.4.6 FlowGraphModeling-NonClassic. . . . . . . . . . . . . . . . . . . 432 8.4.7 NetworkFlowinProgrammingContests . . . . . . . . . . . . . . . . 433 8.5 GraphMatching. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 8.5.1 OverviewandMotivation . . . . . . . . . . . . . . . . . . . . . . . . 435 8.5.2 GraphMatchingVariants . . . . . . . . . . . . . . . . . . . . . . . . 435 8.5.3 UnweightedMCBM. . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 8.5.4 WeightedMCBMandUnweighted/WeightedMCM . . . . . . . . . . 439 8.6 NP-hard/completeProblems . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 8.6.1 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 8.6.2 Pseudo-Polynomial: Knapsack,Subset-Sum,Coin-Change . . . 442 8.6.3 Traveling-Salesman-Problem(TSP) . . . . . . . . . . . . . . . 443 8.6.4 Hamiltonian-Path/Tour . . . . . . . . . . . . . . . . . . . . . . . 445 8.6.5 Longest-Path. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 8.6.6 Max-Independent-SetandMin-Vertex-Cover . . . . . . . . . 447 8.6.7 Min-Set-Cover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453 8.6.8 Min-Path-Cover . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 8.6.9 Satisfiability(SAT). . . . . . . . . . . . . . . . . . . . . . . . . . 455 8.6.10 Steiner-Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457 8.6.11 Graph-Coloring . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459 8.6.12 Min-Clique-Cover . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 8.6.13 OtherNP-hard/completeProblems . . . . . . . . . . . . . . . . . . . 461 8.6.14 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462 8.7 ProblemDecomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 8.7.1 TwoComponents: BinarySearchtheAnswerandOther . . . . . . . 465 8.7.2 TwoComponents: InvolvingEfficientDataStructure . . . . . . . . . 467 8.7.3 TwoComponents: InvolvingGeometry . . . . . . . . . . . . . . . . . 468 8.7.4 TwoComponents: InvolvingGraph . . . . . . . . . . . . . . . . . . . 468 8.7.5 TwoComponents: InvolvingMathematics . . . . . . . . . . . . . . . 468 8.7.6 TwoComponents: GraphPreprocessingandDP . . . . . . . . . . . . 469 8.7.7 TwoComponents: Involving1DStaticRSQ/RMQ . . . . . . . . . . 470 8.7.8 Three(orMore)Components . . . . . . . . . . . . . . . . . . . . . . 470 8.8 SolutiontoNon-StarredExercises . . . . . . . . . . . . . . . . . . . . . . . . 478 8.9 ChapterNotes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480 v CONTENTS c Steven,Felix,Suhendry (cid:13) 9 Rare Topics 481 9.1 OverviewandMotivation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481 9.2 SlidingWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483 9.3 SparseTableDataStructure . . . . . . . . . . . . . . . . . . . . . . . . . . . 485 9.4 SquareRootDecomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . 488 9.5 Heavy-LightDecomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . 493 9.6 TowerofHanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496 9.7 MatrixChainMultiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . 497 9.8 LowestCommonAncestor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 9.9 TreeIsomorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501 9.10 DeBruijnSequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 9.11 FastFourierTransform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508 9.12 Pollard’srhoAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 9.13 ChineseRemainderTheorem. . . . . . . . . . . . . . . . . . . . . . . . . . . 530 9.14 Lucas’Theorem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534 9.15 RareFormulasorTheorems . . . . . . . . . . . . . . . . . . . . . . . . . . . 536 9.16 CombinatorialGameTheory . . . . . . . . . . . . . . . . . . . . . . . . . . . 538 9.17 GaussianEliminationAlgorithm. . . . . . . . . . . . . . . . . . . . . . . . . 543 9.18 ArtGalleryProblem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546 9.19 ClosestPairProblem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547 9.20 A*andIDA*: InformedSearch . . . . . . . . . . . . . . . . . . . . . . . . . 548 9.21 PancakeSorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551 9.22 EggDroppingPuzzle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554 9.23 DynamicProgrammingOptimization . . . . . . . . . . . . . . . . . . . . . . 558 9.24 Push-RelabelAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 9.25 MinCost(Max)Flow. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571 9.26 Hopcroft-KarpAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573 9.27 Kuhn-MunkresAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574 9.28 Edmonds’MatchingAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . . 577 9.29 ChinesePostmanProblem . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580 9.30 ConstructiveProblem. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582 9.31 InteractiveProblem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585 9.32 LinearProgramming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586 9.33 GradientDescent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589 9.34 ChapterNotes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590 Bibliography 593 vi Authors’ Profiles Steven Halim, PhD1 [email protected] StevenHalimisaseniorlecturerinSchoolofComput- ing,NationalUniversityofSingapore(SoC,NUS).He teaches several programming courses in NUS, rang- ingfrombasicprogrammingmethodology,intermedi- atetoharddatastructuresandalgorithms,webpro- gramming, and also the ‘Competitive Programming’ modulethatusesthisbook. Heisthecoachofboth the NUS ICPC teams and the Singapore IOI team. He participated in several ICPC Re- gionals as a student (Singapore 2001, Aizu 2003, Shanghai 2004). So far, he and other trainers@NUShavesuccessfullygroomedvariousICPCteamsthatwontendifferentICPC Regionals(seebelow),advancedtoICPCWorldFinalseleventimes(2009-2010;2012-2020) with current best result of Joint-14th in ICPC World Finals Phuket 2016 (see below), as wellassevengold,nineteensilver,andfifteenbronzeIOImedalists(2009-2019). Heisalso the Regional Contest Director of ICPC Asia Singapore 2015+2018 and is the Deputy Di- rector+InternationalCommitteememberfortheIOI2020+2021inSingapore. Hehasbeen invited to give international workshops about ICPC/IOI at various countries, e.g., Bolivia ICPC/IOIcampin2014,SaudiArabiaIOIcampin2019,CambodiaNOIcampin2020. Steven is happily married to Grace Suryani Tioso and has two daughters and one son: JaneAngelinaHalim,JoshuaBenHalim,andJemimahCharissaHalim. ICPC Regionals # Year(s) AsiaJakarta 5 2013(ThanQ),2014(ThanQ+),2015(RRwatameda), 2017(DomiNUS),2019(SendBobstoAlice) AsiaManila 2 2017(Pandamiao),2019(7Halim) AsiaNakhonPathom 1 2018(Pandamiao) AsiaYangon 1 2018(3body2) AsiaKualaLumpur 1 2019(3body3) Table1: NUSICPCRegionalsWinsin2010s ICPCWorldFinals Team Name Rank Year Phuket,Thailand RRwatameda Joint-14/128 2016 Ekaterinburg,Russia ThanQ+ Joint-19/122 2014 RapidCity,USA TeamTam Joint-20/133 2017 Table2: NUSICPCWorldFinalsTop3Resultsin2010s 1PhDThesis: “AnIntegratedWhite+BlackBoxApproachforDesigningandTuningStochasticLocal SearchAlgorithms”,2009. vii AUTHORS’PROFILES c Steven,Felix,Suhendry (cid:13) Felix Halim, PhD2 [email protected] Felix Halim is a senior software engineer at Google. While in Google, he worked on distributed system problems,dataanalysis,indexing,internaltools,and database related stuff. Felix has a passion for web development. He created uHunt to help UVa on- line judge users find the next problems to solve. He also developed a crowdsourcing website, https: //kawalpemilu.org, to let the Indonesian public to overseeandactivelykeeptrackoftheIndonesiagen- eralelectionin2014and2019. Asacontestant,FelixparticipatedinIOI2002Ko- rea(representingIndonesia),ICPCManila2003-2005, Kaohsiung2006, andWorldFinalsTokyo2007(rep- resenting Bina Nusantara University). He was also one of Google India Code Jam 2005 and 2006 final- ists. Asaproblemsetter,FelixsetproblemsforICPC Jakarta2010,2012,2013,ICPCKualaLumpur2014, andseveralIndonesiannationalcontests. FelixishappilymarriedtoSiskaGozali. ThepictureontherightisoneoftheirEurope honeymoontravelphotos(inSwitzerland)afterICPCWorldFinals@Porto2019. Formore informationaboutFelix,visithiswebsiteathttps://felix-halim.net. Suhendry Effendy, PhD3 suhendry.eff[email protected] Suhendry Effendy is a research fellow in the School of Computing of the National University of Singa- pore (SoC, NUS). He obtained his bachelor degree inComputerSciencefromBinaNusantaraUniversity (BINUS),Jakarta, Indonesia, andhisPhDdegreein ComputerSciencefromNationalUniversityofSinga- pore, Singapore. BeforecompletinghisPhD,hewas a lecturer in BINUS specializing in algorithm anal- ysis and served as the coach for BINUS competitive programmingteam(nicknamedas“Jollybee”). Suhendry is a recurring problem setter for the ICPCAsiaJakartasincetheveryfirstin2008. From 2010 to 2016, he served as the chief judge for the ICPC Asia Jakarta collaborating with many other problemsetters. Healsosetproblemsinmanyother contests, such as the ICPC Asia Kuala Lumpur, the ICPCAsiaSingapore,andOlimpiadeSainsNasional bidangKomputer(IndonesiaNationalScienceOlympiadinInformatic)tonamebutafew. 2PhDThesis: “SolvingBigDataProblems: fromSequencestoTablesandGraphs”,2012. 3PhDThesis: “GraphPropertiesandAlgorithmsinSocialNetworks: Privacy, SybilAttacks, andthe ComputerScienceCommunity”,2017. viii Chapter 5 Mathematics Weallusematheveryday;topredictweather,totelltime,tohandlemoney. Mathismorethanformulasorequations;it’slogic,it’srationality, it’susingyourmindtosolvethebiggestmysteriesweknow. — TV show NUMB3RS 5.1 Overview and Motivation Theappearanceofmathematics-relatedproblemsinprogrammingcontestsisnotsurprising sinceComputerScienceisdeeplyrootedinMathematics. Manyinterestingreallifeproblems canbemodeledasmathematicalproblemsasyouwillfrequentlyseeinthischapter. RecentICPCproblemsets(basedonourexperienceinAsianRegionals)usuallycontain one or two mathematical problems. Recent IOIs usually do not contain pure mathematics tasks, but many tasks do require mathematical insights. This chapter aims to prepare contestantsindealingwithmanyofthesemathematicalproblems. We are aware that different countries place different emphases in mathematics training in pre-University education. Thus, some contestants are familiar with the mathematical terms listed in Table 5.1. But for others, these mathematical terms do not ring a bell, perhapsbecausethecontestanthasnotlearntitbefore,orperhapsthetermisdifferentin the contestant’s native language. In this chapter, we want to make a more level-playing field for the readers by listing as many common mathematical terminologies, definitions, problems,andalgorithmsthatfrequentlyappearinprogrammingcontestsaspossible. ArithmeticProgression GeometricProgression Polynomial Algebra Logarithm/Power BigInteger NumberTheory PrimeNumber SieveofEratosthenes Miller-Rabin GreatestCommonDivisor LowestCommonMultiple Factorial EulerPhi ModifiedSieve ExtendedEuclidean LinearDiophantine ModularInverse Combinatorics Fibonacci GoldenRatio Binet’sFormula Zeckendorf’sTheorem PisanoPeriod BinomialCoefficients Fermat’slittletheorem Lucas’Theorem CatalanNumbers Inclusion-Exclusion ProbabilityTheory Cycle-Finding GameTheory Zero-SumGame DecisionTree PerfectPlay Minimax NimGame Sprague-GrundyTheorem MatrixPower Table5.1: Listofsome mathematicaltermsdiscussedinthischapter 273 5.2. ADHOCMATHEMATICALPROBLEMS c Steven,Felix,Suhendry (cid:13) 5.2 Ad Hoc Mathematical Problems We start this chapter with something light: the Ad Hoc mathematical problems. These areprogrammingcontestproblemsthatrequirenomorethanbasicprogrammingskillsand some fundamental mathematics. As there are still too many problems in this category, we furtherdividethemintosub-categories,asshownbelow. Theseproblemsarenotplacedin Book1astheyareAdHocproblemswith(heavier)mathematicalflavor. Butrememberthat manyoftheseAdHocmathematicalproblemsaretheeasierones. Todowellintheactual programmingcontests,contestantsmustalsomastertheothersections ofthischapter. Finding(Simple)FormulaorPattern • These problems require the problem solver to read the problem description carefully togetasimplifiedformulaortospotthepattern. Attackingthemdirectlywillusually result in a TLE verdict. The actual solutions are usually short and do not require loopsorrecursions. Example: LetsetS beaninfinitesetofsquareintegers: 1,4,9, { 16, 25, ... . Given an integer X (1 X 1018), count how many integers in S are } ≤ ≤ lessthanX. Theanswerissimply: √X 1 . ThisisanO(1)solution. b − c Note that in Section 5.4, we will discuss Combinatorics problems that will also end up with some (not necessarily simple) formula. We also have Section 9.15 where we discussafewknownbutveryraremathematicalformulas. BaseNumberConversionorVariants • Thesearethemathematicalproblemsinvolvingbasenumbers. Themostfrequenttype involvesthestandard conversionproblemsthatcanbeeasilysolvedmanuallyorwith C/C++/Python/OCaml(limited)orJavaInteger/BigInteger(mostgeneric)library. Forexample,toconvert132inbase8(octal)intobase2(binary),wecanusebase10 (decimal)astheintermediatestep: (132) is1 82+3 81+2 80=64+24+2=(90) 8 × × × 10 and (90) is 90 45(0) 22(1) 11(0) 5(1) 2(1) 1(0) 0(1) = 10 → → → → → → → (1011010) (thatis,divideby2until0,thenreadtheremaindersfrombackwards). 2 However,wecanalsousebuilt-inlibraries: – C/C++: int v; scanf("%o", &v); // read v in octal bitset<32> bin(v); // use bitset printf("%s\n", bin.to_string().c_str()); // print in binary – Python: print("{0:b}".format(int(str(input()), 8))) # octal to binary – OCaml: Printf.sprintf "%X" (int_of_string "0o374");; # octal to hexa – Java: If we know Java Integer/BigInteger class, we can actually construct an instance ofInteger/BigIntegerclassinanybase(radix)anduseitstoString(int radix) methodtoprintthevalueofthatinstanceinanybase(radix). Thisisamuchmore flexiblelibrarysolutionthanC/C++orPythonsolutionsearlierthatarelimited to popular bases = 2/8/10/16. See an example below for Kattis - basicremains (also available at UVa 10551 - Basic Remains). Given a base b and two non- negativeintegerspandm—bothinbaseb,computep%mandprinttheresult asabasebinteger. Thesolutionisasfollows: 274

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.