Skip to content

Repository files navigation

Check out the USACO Guide to get better at competitive programming!

Speed up compile times: https://codeforces.com/blog/entry/53909

g++ -std=c++11 /usr/include/path_to/bits/stdc++.h

Competitive Programming Solutions

This repository contains solutions to various competitive programming problems.

Command to find problems solved:

find -type f -name "*.cpp" ! -name "*main*" -not -path "./cpbook-code/*" -not -path "./alphastar/*summer*/*" -not -path "./**/*game*/*" | wc -l

Note: Nothing below is kept up to date anymore!!

USACO Solutions

Solutions to USACO training and USACO contest problems.

USACO Training:

Problem NumberProblem NameSolution Notes
1.5.1Arithmetic ProgressionsCareful Brute Force
1.6.3Superprime RibBrute force
2.1.1The CastleFloodfill to assign each room a number
2.1.2Ordered FractionsGenerate all possible fractions
2.1.3Sorting A Three-Valued SequenceNotes written as comments in code
2.1.4Healthy HolsteinsBrute force
2.1.5Hamming CodesBrute force
2.2.1Preface NumberingBrute force
2.2.2Subset SumsDP
2.2.3Runaround NumbersBrute force
2.2.4Party LampsBrute force 2^4, doesn't matter if you press button twice
2.3.1Longest PrefixDP
2.3.2Cow PedigreesDP
2.3.3Zero SumBrute force (DFS)
2.3.4Money SystemsDP (VN)
2.3.5Controlling CompaniesRecursion
2.4.1The Tamworth TwoBrute force, maximum (100*4)^2 steps before "impossible"
2.4.2Overfencingrun shortest path BFS on two exit nodes
2.4.3Cow ToursDijkstra
2.4.4Bessie Come HomeDijkstra
2.4.5Fractions to DecimalsRecursion
3.1.1Agri-NetPrim's (or Kruskal)
3.1.2Score InflationKnapsack
3.1.3Humble NumbersCreate size N set of possible numbers, brute force
3.1.4ContactBrute force
3.1.5StampsDP
3.2.1FactorialsCount number of twos and fives
3.2.2StringsobitsDefine dp(i, j) = # of numbers with i bits and at most j ones
3.2.3Spinning WheelsBrute Force, max 360 seconds
3.2.4Feed RatiosBrute force
3.2.5Magic SquaresBFS
3.2.6Sweet ButterAPSP
3.3.1Riding the FencesEulerian Path
3.3.2Shopping OffersDijkstra
3.3.3CamelotBrute force, king can take only two steps
3.3.4Home on the RangeDP
3.3.5A GameDP
3.4.1American HeritageRecursively generate tree
3.4.2Electric FencePick's Theorem
3.4.3Raucous RockersBrute Force (Bitmasking)
4.1.1Beef McNuggetsDP
4.1.2Fence LoopsDijkstra
4.2.1Drainage DitchesMax Flow O(V^2E)
4.2.2The Perfect StallMax Bipartite Matching
4.2.3Job ProcessingGreedy
4.3.1Buy Low, Buy LowerDP, BigInteger (less than + addition)
4.3.2Street RaceDFS, Set, Brute Force
4.3.3Letter GameString permutation, brute force, map/set
4.4.1Shuttle PuzzleBrute Force, BFS (Queue), Implementation
4.4.2Pollutant ControlMax Flow Min Cut, minimize removed edges
4.4.3Frame UpAll Topological Sorts
5.1.1Fencing the CowsSimple Convex Hull
5.1.2Starry NightFloodfill, Implementation
5.1.3Musical ThemesSliding Window Iterative DP, Longest Repeating Non-Overlapping Substring, deltas
5.2.1Snail TrailBrute Force, Implementation, Recursion
5.3.1Milk MeasuringDP, Optimization, Sliding Window
5.3.2Window AreaImplementation, Calculating overlapping rectangle area - Split rectangle into four parts
5.3.3Network of SchoolsMin additional edges to form SCC
5.3.4Big BarnPrefix Sums + Binary Search, doable with DP as well
5.4.1Canada TourDP
5.4.2Character RecognitionDP, Bit manipulation for Optimization/Pruning
5.4.3TeleCowmunicationMax Flow Min Cut, Split Nodes
5.5.1PictureLine Sweep
5.5.2Hidden PasswordsString Processing
5.5.3Two FiveDP

Silver USACO Contests:

Contest DateProblem IDProblem NameSolution Notes
Feb 2018reststopsRest StopsGreedy
Feb 2019revegetateThe Great RevegetationGraph, DFS, Tricky

Gold USACO Contests:

Old USACO Gold (Silver):

Contest DateProblem IDProblem NameSolution Notes
Nov 2012clumsyClumsy CowsGreedy
Nov 2012distantDistant PasturesAPSP, dijkstra
Nov 2012bbreedsBalanced Cow BreedsSame problem as Gold
Dec 2012crazyCrazy FencesComputational Geometry
Dec 2012wifiWifi SetupDP
Dec 2012mrouteMilk RoutingDijkstra
Jan 2013paintPainting the FenceCoordinate Compression, Store Deltas & Sweep
Jan 2013squaresSquare OverlapSweep
Jan 2013inviteParty Invitationsprecompute which groups each cow is in
Feb 2013perimeterPerimeterOptimized Floodfill
Feb 2013tractorTractorBinary search for answer, dfs
Feb 2013mschedMilk SchedulingGreedy
Mar 2013pokerPoker HandsGreedy
Mar 2013paintingFarm PaintingSweep
Mar 2013cowrunThe Cow RunDP, same as gold
Open 2013gravityWhat's Up With Gravity?Dijkstra
Open 2013fuelFuel EconomyGreedy
Open 2013cruiseLuxury River CruiseFind where sequence repeats
Nov 2013nocowFarmer John has no Large Brown CowSolvable with a bit of math
Nov 2013crowdedCrowded CowsSweep, can use multiset instead of monotonic queue
Nov 2013pogocowPogo-CowDP, note that Bessie can go either direction
Dec 2013mschedMilk SchedulingGreedy, sweep
Dec 2013vacationVacation PlanningCode is slightly modified from gold version, answer is unnecessarily complicated for silver
Dec 2013shuffleThe Bessie ShuffleRepeated Squaring, Permutations, Composing functions/permutations
Jan 2014slowdownBessie Slows DownMaintain two arrays, simulation
Jan 2014ccskiCross Country SkiingPrim's
Jan 2014recordingRecording the MoolympicsGreedy
Feb 2014autoAuto-completeBinary search
Feb 2014rblockRoadblockDijkstra
Feb 2014scodeSecret CodeDP
Mar 2014irrigationWatering the FieldsKruskal/MST
Mar 2014lazyThe Lazy CowRotate grid 45 degrees
Mar 2014mooomooMooo MooDP
Open 2014fairphotoFair PhotographySweep
Open 2014gpsduelDueling GPSsDijkstra
Open 2014odometerOdometerDP Construction
Dec 2014piggybackPiggy BackShortest Path on three nodes
Dec 2014marathonMarathonDP
Dec 2014cowjogCow JogSweep
Jan 2015stampedeStampedeSweep
Jan 2015cowrouteCow RoutingDijkstra
Jan 2015meetingMeeting TimeDP
Feb 2015censorCensoringRolling Hash
Feb 2015hopscotchCow HopscotchDP
Feb 2015superbullSuperbullMST, Prim's O(V^2)
Open 2015bgmBessie Goes MooParity
Open 2015trappedTrapped in the Haybales (Silver)Sort, Sweep
Open 2015buffetBessie's Birthday Buffet

USACO Gold (2015-now)

Contest DateProblem IDProblem NameSolution Notes
Dec 2015cardgameHigh Card Low Card (Gold)Greedy
Dec 2015feastFruit FeastDP (Knapsack)
Dec 2015dreamBessie's DreamDijkstra
Jan 2016angryAngry CowsSweep/Greedy/DP, Binary Search (Optional)
Jan 2016radioRadio ContactDP
Jan 2016lightsoutLights OutSimulation, Coordinates, Brute Force, Implementation
Feb 2016cbarnCircular BarnGreedy
Feb 2016cbarn2Circular Barn (Revisited)DP
Feb 2016fencedinFenced InMST (Kruskal)
Open 2016splitSplitting The FieldSweep
Open 2016closingClosing The FarmUFDS (Note: Runs really close to time limit)
Open 2016248248DP
Dec 2016moocastMoocastUFDS, brute force
Dec 2016checklistCow ChecklistDP
Dec 2016lasersLasers and MirrorsBFS
Jan 2017bphotoBalanced PhotoFenwick Tree
Jan 2017hpsHoof, Paper, Scissors3D DP
Jan 2017cownavCow NavigationBFS
Feb 2017visitfjWhy Did The Cow Cross The RoadDijkstra
Feb 2017nocrossWhy Did The Cow Cross The Road IIDP
Feb 2017circlecrossWhy Did The Cow Cross The Road IIIFenwick Tree (BIT)
Open 2017cownomicsBovine GenomicsRolling Hash
Open 2017art2Modern Art 2Calculate start/end points
Dec 2017piepieA Pie For A PieBFS, binary search
Dec 2017barnpaintingBarn PaintingDP
Dec 2017hayfeastHaybale FeastTwo Pointers
Jan 2018mootubeMooTubeUFDS
Jan 2018atlargeCow At LargeDFS/BFS
Jan 2018spaintingStamp PaintingDP, recurrence
Feb 2018snowbootsSnow BootsSort, Doubly-Linked List
Feb 2018dirtraverseDirectory TraversalDFS
Feb 2018tamingTaming The HerdDP
Open 2018sortOut of SortsBIT
Open 2018milkorderMilking OrderTopological Sort (Lexicographically earliest)
Open 2018talentTalent ShowBinary search for answer, DP
Dec 2018diningFine DiningDijkstra
Dec 2018cowpatibilityCowpatibilityPIE
Dec 2018teamworkTeamworkDP
Jan 2019poetryCow PoetryDP, power under mod, math
Jan 2019sleepySleepy Cow SortingFenwick Tree
Jan 2019shortcutShortcutDijkstra, find path
Feb 2019cowlandCow LandTree Traversal Array, or alternatively Heavy-Light Decomposition
Feb 2019dishesDishwashingGreedy (Also doable with Greedy + Binary Search)
Feb 2019paintbarnPainting the BarnGeometry, Prefix Sums, Line Sweep
Open 2019balanceBalancing Inversions

Platinum USACO Contests:

Old USACO Platinum (Gold):

Contest DateProblem IDProblem NameSolution Notes
Nov 2012bbreedsBalanced Cow BreedsDP
Nov 2012cbsConcurrently Balanced StringsPrefix Sums
Dec 2012gangsGangs of Istanbull/CowstantinopleGreedy
Dec 2012firstFirst!trie, checking DAG for cycles
Dec 2012runawayRunning Away From the Barn
Jan 2013lineupCow Lineupsweep with two pointers
Jan 2013islandIsland Travelsbfs
Jan 2013seatingSeatingBinary Tree, Lazy Propagation
Feb 2013partitionPartitioning The FarmDP
Feb 2013taxiTaxiMin Cost Matching, calculate distance driven w/o cow
Feb 2013routeRoute DesigningDP
Mar 2013cowrunThe Cow RunDP
Mar 2013hillwalkHill WalkLine sweep, find a way to order hills
Nov 2013nochangeNo ChangeDP, 2^k state
Nov 2013sightLine of SightIf two cows can see the same point on the silo, they can see each other
Nov 2013emptyEmpty StallsSweep
Dec 2013vacationgoldVacation Planning (Gold)Dijkstra
Dec 2013optmilkOptimal MilkingBinary Tree
Jan 2014skicourseBuilding A Ski CourseDP
Jan 2014skilevelSki Course RatingKruskal
Feb 2014rblockRoadblockDijkstra
Feb 2014decCow DecathlonDP
Mar 2014sabotageSabotageBinary search, 1D max sum
Mar 2014fcountCounting FriendsBrute Force, greedily connect friends
Dec 2014guardGuard MarkDP
Dec 2014marathonMarathonSegment Tree
Dec 2014cowjogCow JogLongest Non-Increasing Subsequence
Jan 2015cowrectCow RectanglesSweep, assume we have to take one of the Holsteins
Jan 2015movieMoovie MoovingDP, bitmasking
Open 2015palpathPalindromic PathsDP
Open 2015trappedTrapped in the HaybalesSort haybales by weight
Open 2015buffetBessie's Birthday BuffetDP

USACO Platinum (2015-now):

Contest DateProblem IDProblem NameSolution Notes
Dec 2015maxflowMax FlowLCA, prefix sums
Dec 2015cardgameHigh Card Low CardGreedy
Dec 2015haybalesCounting HaybalesSeg Tree, Lazy, Min Query & Sum Query
Jan 2016fortmooFort MooDP/Sliding Window
Jan 2016mowingMowing The Field2D Range Tree
Feb 2016balancingLoad BalancingBinary Search, BIT
Feb 2016fencedinplatFenced In
Open 2016262144262144DP
Dec 2016teamTeam BuildingDP
Jan 2017promotePromotion CountingBIT on preorder of tree
Jan 2017tallbarnBuilding a Tall BarnBinary Search
Jan 2017subrevSubsequence ReversalDP
Feb 2017mincrossWhy Did The Cow Cross The RoadFenwick Tree
Feb 2017nocrossWhy Did The Cow Cross The Road IIDP, RMQ (Seg Tree)
Feb 2017friendcrossWhy Did The Cow Cross The Road III2D Seg Tree
Open 2017artModern ArtPrefix Sums/Deltas
Open 2017grassSwitch GrassMST, Sets, I/O Optimization
Dec 2017pushaboxPush A BoxBiconnected Components, BFS
Dec 2017greedyGreedy Gift TakersBinary Search, Prefix Sums
Open 2018disruptDisruptionMethod 1: (Merging small to large, pool pointers method). Method 2: (LCA + Path Compression). Method 3: (HLD). Method 4: (2D Seg Tree, Graphically thinking)
Dec 2018balanceBalance BeamConvex Hull / Visualizing Geometry
Jan 2018lifeguardsLifeguardsDP (Note: Solution code is very sketchy and really shouldn't run in time)
Feb 2018newbarnNew BarnsCentroid Decomposition
Jan 2019redistrictingRedistrictingDP, Monotonic Queue
Feb 2019cowdateCow DatingTwo pointers, math
Open 2019treeboxesTree BoxesLCA, Implementation, Interactive

Codeforces

Solutions to various Codeforces problems. List no longer updated!

Here is the complete solutions folder.

Problem IDProblem NameSolution Notes
321CC. Ciel the CommanderCentroid Decomposition
342EE. Xenia and TreeCentroid Decomposition, LCA
383DD. AntimatterDP
497AA. Reorder The ArrayMultiset
762BB. USB vs PS/2Sorting, Greedy
762EE. Radio StationsSegment Tree
809AA. Do you want a date?Math, power, mod
817DD. Imbalanced ArrayStack, Sweep, Math
937AA. OlympiadSet
946DD. TimetableDP
989DD. A Shade of MoonlightBinary Search, Math
991BB. Getting an ASorting
1012BB. Chemical tableBipartite Graph
1038CC. Gambling
1061DD. TV ShowsMultiset, Greedy
1067BB. Multihedgehog
1095FF. Make it ConnectedUFDS
1098AA. Sum in the tree
1099FF. CookiesFenwick Tree
1104AA. Splitting into digitsbrute force
1104BB. Game with stringStack
1104CC. Grid GameAd Hoc
1104DD. Game with modulobinary search, math
1105AA. Salem and Sticks
1105BB. Zuhair and Strings
1105CC. Ayoub and Lost Array
1105DD. Kilani and the Game
1111AA. Superhero Transformation
1111CC. Creative Snap
1113AA. Sasha and His TripGreedy
1113BB. Sasha and Magnetic Machines
1113CC. Sasha and a Bit of Relax
1113DD. Sasha and One More Name
1114DD. Flood Fill
1117EE. Decypher the StringMath, string processing
1118EE. Yet Another Ball ProblemConstructive Algorithms, Ad Hoc
1130AA. Be PositiveAd Hoc
1130BB. Two CakesGreedy
1130CC. ConnectFloodfill, Brute Force
1130D1D. Toy Train (Simplified)Simulation
1130D2D. Toy TrainMath, Precomputation
1131DD. Gourmet ChoiceDAG, Detecting Cycles, Topo Sort
1132DD. Stressful TrainingBinary Search, Greedy, Implementation
1133F1F1. Spanning Tree With Maximum DegreeGreedy, UFDS, Kruskal
1133F2F2. Spanning Tree With One Fixed DegreeGreedy, UFDS, Kruskal, Construction
1137DD. Cooperative GameMath, Number Theory, Mods
1139EE. Maximize MexBipartite Graph, Flow
1141F1F1. Same Sum Blocks (Easy)See 1141F2, though O(N^4) dp should also work
1141F2F2. Same Sum Blocks (Hard)Prefix sums O(N^2)
1141GG. Privatization of Roads in TreelandGreedy, Implementation, DFS
1151AA. Maxim and BiologyBrute Force
1151BB. Dima and a Bad XORBrute Force, XOR (Note: Solution code is brute force/DP but a O(n*m) solution exists with observation)
1151CC. Problem for NazarMath, Implementation
1151DD. Stas and the Queue at the BuffetGreedy, light math
1153AA. Serval and BusMath
1153BB. Serval and Toy BricksGreedy
1153CC. Serval and Parenthesis SequenceGreedy
1153DD. Serval and Rooted TreeTree traversal, DP (ish)
1153EE. Serval and SnakeBinary Search, Brute Force
1169DD. Good TripleBrute Force
1173AA. Nauuo and VotesGreedy
1173BB. Nauuo and ChessGreedy, Constructive Algorithms
1173CC. Nauuo and CardsGreedy
1173DD. Nauuo and CircleCombinatorics, DP, trees
1173E1E1. Nauuo and Pictures (easy version)DP, probability, Modular Multiplicative Inverses
1176AA. Divide ItBrute Force, Recursion
1176BB. Merge ItGreedy
1176CC. Lose ItGreedy
1176DD. Recover Itmultiset, prime generation, greedy
1176EE. Cover ItBicoloring (ish)
1181AA. Chunga-Changa
1181BB. Split a Number
1181CC. Flag
1181DD. Irrigation

International Olympiad in Informatics (IOI)

Problem NameSolution Notes
2003 A. Trail MaintenanceUnion Find
2004 B. HermesDP, Iterative, Sliding Window
2004 D. EmpodiaRead header of file, IDK why solution gets AC :P
2014 E. FriendInduction Trick

Solutions Folder

UVa Online Judge (Competitive Programming 3, Starred)

Solutions to UVa Online Judge problems. Mostly starred problems from Competitive Programming 3.

Solutions Folder

Google Kick Start

Solutions to various Google Kick Start competitions.

Problem NameSolution Notes
A - Even DigitsAd Hoc
A - Lucky DipBrute Force / Binary Search
A - Scrambled WordsStrings, implementation
B - No NineDigit DP (Alternatively, Ad Hoc)
Problem NameSolution Notes
A - TrainingSorting, Prefix Sums
A - ParcelsMulti-Source BFS, Manhattan Distance
B - Building PalindromesPrefix Sums
B - Energy StonesDP Knapsack, sorting
B - Diverse SubarraySegment Tree

Google Code Jam

Solutions to various Google Code Jam competitions.

RoundProblem NameSolution Notes
1AWaffle ChoppersPrefix sums, greedy
1ABit PartyBinary Search
2Falling BallsImplementation
RoundProblem NameSolution Notes
QualificationForegone SolutionGreedy
QualificationYou Can Go Your Own WayGreedy
QualificationCryptopangramsGCD, BigInteger, Math
QualificationDat BaeInteractive, similar strategy to CodeForces 1117E
1APylonsConstruction, Implementation
1AGolf GophersChinese Remainder Theorem
1BManhattan Crepe CartSweep lines
1BDraupnir (Visible Set Only)Solving systems of equations (math)
1BFair FightSegment Tree, Binary Search

CSES

Solutions to CSES Problem Set.

Problem NameSolution Notes
Weird AlgorithmSimulation, careful with integer overflow
Missing NumberBasic Arrays
RepetitionsMaximum length substring with same characters
Increasing ArrayGreedy
PermutationsAd Hoc, Construction

Solutions Folder

About

Solutions to various competitive programming problems I've solved. Check out the USACO Guide to improve at competitive programming!

Topics

Resources

Stars

87 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages