Problems

Pick a problem and write your solution in the built-in editor. The judge runs it against real test cases while you watch, and the wider archive is open to read whenever you like.

Total results837 problems
TitleLevelTopicsSolvedTime limitMemory limitJudge
All Roads Lead Where?Given a tree of cities rooted at Rome and query pairs, print the unique shortest path between each pair as the first letters of the cities on the route.Medium5TreeDFS+2No attempts yet1s128 MBJudgeable
Tree CuttingOn a tree of N nodes, print every node whose removal leaves each connected piece with at most floor(N/2) nodes, or NONE.Medium5TreeDFS+2No attempts yet1s128 MBJudgeable
Reconstructing Binary TreesGiven the pre-order and in-order traversals of a binary tree with distinct labels, print its post-order traversal or report that no tree matches.Medium5TreeRecursion+2No attempts yet1s128 MBJudgeable
RailwayGiven a weighted tree, compute the total weight of the unique path between each queried pair of cities.Medium5TreePrefix sum+1No attempts yet1s32 MBJudgeable
Ants and the LadybugSimulate guards moving on a tree toward successive ladybug landings, respecting blocking rules, and report each ant's final place and chase count.Medium5TreeSimulation+2No attempts yet1s128 MBJudgeable
WarehousesMove goods along tree roads so every warehouse holds the average amount at minimum transport cost.Medium5TreeGreedy+1No attempts yet1s512 MBJudgeable
Chinese RestaurantsPick the intersection that minimizes the farthest distance to a marked restaurant and report that distance, or -1 when no restaurant exists.Medium5TreeBFSNo attempts yet1s128 MBJudgeable
Jas the WormA rooted tree grows one leaf at a time while Jas steps once toward each queried vertex, and the task reports his landing vertex after every move.Medium5TreeBinary searchNo attempts yet1s128 MBJudgeable
MinersAssign each miner to a leaf chamber whose path from the entrance stays tall enough and fit as many miners as possible.Medium5GreedySorting+1No attempts yet2s128 MBJudgeable
Message BroadcastingCompute the fewest rounds to spread a message from the root when each informed node calls at most one child per round.Medium5GreedyTree+2No attempts yet1s128 MBJudgeable
Hierarchical DemocracyCompute the smallest popular vote total that wins the presidency through nested majority votes in districts.Medium5TreeGreedy+1No attempts yet1s128 MBJudgeable
Frozen SprinklersCut pipes with minimum total force so no water flows from the central node to any leaf sprinkler in the tree.Medium5Dynamic programmingTree+1No attempts yet3s128 MBJudgeable
deltreeFrom a log of cd and dir commands, find the minimum space a final deltree command is guaranteed to free.Medium5TreeSimulationNo attempts yet1s128 MBJudgeable
Prefix-Free SubsetsCount the subsets of the given word set in which no word is a prefix of another word.Medium5TrieDynamic programming+1No attempts yet1s128 MBJudgeable
CSS Selector MatchingGiven a nested div document and up to five CSS selectors with descendant and child combinators, print the matching element ids in document order.Medium5TreeDFS+1No attempts yet10s256 MBJudgeable
Fuleco and the AntGiven positions A and B and a U/D string encoding depth changes along a tree walk, output the tree distance between the two forks.Medium5TreePrefix sum+1No attempts yet1s64 MBJudgeable
Intrepid climberStarting from the root of a weighted tree, visit all marked nodes with free descents and costly climbs at minimum total energy.Medium5TreeDFS+1No attempts yet3s256 MBJudgeable
Preorder TraversalsDecide whether each given number list is the preorder traversal of some binary search tree.Medium5StackTreeNo attempts yet1s256 MBJudgeable
Salary InequitySubtree raises add an amount to every salary below an employee, and each query asks for the max minus min salary in that subtree.Medium5Segment treeTreeNo attempts yet10s256 MBJudgeable
Super Pipes and Ant FeedingFind the smallest amount of liquid to pour into the root of a tree so percentage splits with optional squaring pipes still meet every leaf demand.Medium5Dynamic programmingTree+1No attempts yet1s32 MBJudgeable
Breadth-First Search by FoxpowerCompute the total distance walked visiting every vertex of a rooted tree in BFS order starting at the root.Medium5TreeBFSNo attempts yet2s128 MBJudgeable
MobileGiven a tree of balanced arms with arm-length ratios, compute the minimum total weight when all weights are integers and one weight has a lower bound.Medium5TreeMath+1No attempts yet1s256 MBJudgeable
KinfolkGiven two positions in a binary family tree and the second person's gender, print the English kinship term of the second to the first.Medium5TreeMath+1No attempts yet1s256 MBJudgeable
A Rational SequenceGiven a reduced fraction p/q from the Calkin-Wilf tree, compute its position n in breadth-first order.Medium5MathTree+1No attempts yet1s256 MBJudgeable
K-ary TreeCompute the edge distance for each query pair in a complete K-ary tree with N nodes numbered in breadth-first order.Medium5TreeMathNo attempts yet1s256 MBJudgeable
Fairland (Small)Marie keeps the largest manager-closed team containing herself whose salaries span at most D.Medium5TreeDFS+2No attempts yet5s512 MBJudgeable
Full Binary TreeGiven a tree with up to 15 nodes, delete as few nodes as possible so the remaining nodes form a full binary tree for some choice of root.Medium5TreeDynamic programming+1No attempts yet5s512 MBJudgeable
Decision Tree (Large)Parse a nested decision tree with optional feature names, then multiply node weights along the path chosen by each animal's features.Medium5StringRecursion+2No attempts yet5s512 MBJudgeable
Cheating a Boolean Tree (Small)Given a complete boolean tree with switchable gates, find the minimum number of gate flips so the root evaluates to V.Medium5TreeDynamic programmingNo attempts yet5s512 MBJudgeable
Cheating a Boolean Tree (Large)Given a complete binary tree of AND/OR gates with fixed leaf values, find the fewest changeable gates to flip so the root equals V, or report IMPOSSIBLE.Medium5Dynamic programmingTree+2No attempts yet5s512 MBJudgeable
Traffic (Small)Given a tree and Q tickets, count how many tickets use each edge along the unique path, then report the edge with the largest count (smallest station pair on ties).Medium5TreePrefix sum+2No attempts yet2s512 MBJudgeable
Bus RoutesOn a tree with N stops, every ordered pair sends a bus along the unique path; for each stop count how many of the N(N-1) buses halt there, including endpoints.Medium5TreeMath+1No attempts yet3s1024 MBJudgeable
Cheating a Boolean TreeIn a tournament-style Boolean tree, flip the fewest changeable AND/OR gates so the root evaluates to V, or report it impossible.Medium5TreeDynamic programmingNo attempts yet2s512 MBJudgeable
Tree with the longest diameterGiven the number of vertices at each level from the root, build a tree realizing those level counts with the maximum possible diameter.Medium5TreeGreedy+2No attempts yet2s512 MBJudgeable
Equal leaf distancesRaise edge weights in a weighted perfect binary tree so every root-to-leaf path has equal length, minimizing the total weight.Medium5TreeGreedy+2No attempts yet1s512 MBJudgeable
A Rational Sequence 3Find the rational number at position N in the breadth-first level-order traversal of the Calkin-Wilf-style binary tree rooted at 1/1, where left and right children are p/(p+q) and (p+q)/q.Medium5TreeMath+2No attempts yet2s512 MBJudgeable
Company Culture 2Given a tree of boss relations, apply subtree-wide praise additions in real time and answer point total queries.Medium5TreeDFS+2No attempts yet5s512 MBJudgeable
Company Culture 3Employees sit in a rooted tree. A praise of w given to employee i from a subordinate adds w to i and every ancestor up to the president; type 2 queries ask an employee's running total.Medium5TreeDFS+2No attempts yet2s512 MBJudgeable
Sweet, sour, bitter, saltyCut edges of a rooted binary tree so that at least X resulting components each contain at least K nodes, minimizing total cut cost.Medium5TreeDynamic programming+2No attempts yet2s512 MBJudgeable
Roasting Emma is a barista tooGiven a weighted tree, compute for every vertex the sum of shortest distances to all other vertices.Medium5TreeDFS+2No attempts yet1.5s128 MBJudgeable
Family TreeGiven a set of mother-child pairs, classify the relationship between two cows as siblings, direct ancestor, aunt, cousins, or unrelated, following a fixed rule order.Medium5GraphDFS+2No attempts yet2s512 MBJudgeable
Seungbeom CorporationMaintain balances on a company mentor tree while updates add a value to one employee and every employee below them.Medium5TreeDFS+1No attempts yet1s256 MBJudgeable
Sheep Rescue OperationGiven a tree rooted at 1 with sheep or wolf counts per node, find the maximum number of sheep that can reach node 1 along unique paths while each wolf eats at most one entering sheep.Medium5TreeGreedy+2No attempts yet1s256 MBJudgeable
BFS Special JudgeGiven a tree and a permutation of its vertices, decide whether the permutation can be produced by a BFS traversal starting from vertex 1.Medium5BFSTree+2No attempts yet2s512 MBJudgeable
Promoting a ClubGiven a forest, choose the fewest vertices so that every vertex is either chosen or adjacent to a chosen one (minimum dominating set on a forest).Medium5TreeDynamic programming+2No attempts yet2s256 MBJudgeable
Big ChangesOn N labeled cities, count the spanning trees whose maximum degree is as large as possible, i.e. the star trees.Medium5CombinatoricsTree+2No attempts yet2s512 MBJudgeable
Unstable SubstancesEach substance conflicts with exactly one other; choose a subset with no conflicting pair to maximize total weight.Medium5GraphDynamic programming+2No attempts yet1.2s256 MBJudgeable
News BroadcastGiven a rooted tree, each informed employee calls one subordinate at a time, each call lasting one minute; find the minimum time until every employee knows the news.Medium6TreeDFS+2No attempts yet2s128 MBJudgeable
Sum of Tree Path WeightsGiven a weighted tree, compute the sum over all vertex pairs of the product of edge weights along their connecting path, modulo 1e9+7.Medium6TreeDFS+2No attempts yet2s128 MBJudgeable
Optimal Binary Search TreeGiven up to 300 distinct keys within range 1..n, build a binary search tree minimizing total node visits over all searches for every integer from 1 to n, using an optimal BST DP with unsuccessful search gaps.Medium6Dynamic programmingTree+1No attempts yet2s128 MBJudgeable
Tree EncodingGiven N and an index, find the k-th lexicographically smallest preorder traversal string among all binary search trees built from the first N letters, using Catalan number counting.Medium6CombinatoricsMath+2No attempts yet2s128 MBJudgeable
Fiibonacci TreeGiven preorder indices of two nodes in a recursively built Fibonacci binary tree, compute the shortest L/R/U path between them without ever materializing the tree.Medium6TreeRecursion+2No attempts yet2s128 MBJudgeable
Tree ColoringGiven a tree, assign colors 1 to n to vertices so adjacent vertices differ, minimizing the total cost equal to the sum of color numbers used.Medium6TreeBFS+2No attempts yet2s256 MBJudgeable
Flattening TablesParse nested HTML-style table layouts and output an equivalent single flat table using rowspan and colspan to preserve row and column alignment.Medium6RecursionTree+2No attempts yet1s128 MBJudgeable
Garden PruningFind the minimum number of edge cuts needed to prune a tree down to exactly m vertices while keeping it connected.Medium6Dynamic programmingTree+1No attempts yet2s128 MBJudgeable
Painting RoofsGiven a tree of houses and M paint costs, assign a color to every house minimizing total cost so that adjacent houses have different colors.Medium6Dynamic programmingTree+2No attempts yet2s128 MBJudgeable
Counting Full Binary TreesCount full binary trees with exactly n nodes and height exactly k, modulo 9901, using a height-bounded DP and subtraction trick.Medium6Dynamic programmingTree+2No attempts yet2s128 MBJudgeable
Excellent VillagesGiven a tree with village populations, choose a maximum-weight independent dominating set (no two chosen villages adjacent, every unchosen village adjacent to a chosen one).Medium6Dynamic programmingTree+1No attempts yet2s128 MBJudgeable
Image CompressionBuild the quadtree of an image padded to the next power-of-two square, then count total nodes and the minimum nodes after sharing identical non-leaf subtrees.Medium6TreeRecursion+2No attempts yet2s128 MBJudgeable
Atomic EnergyGiven a forest built from energy-state vertices connected by edges whose weight equals a proton energy, pick an independent set of vertices maximizing the sum of values (weighted maximum independent set on a forest).Medium6Dynamic programmingTree+1No attempts yet2s128 MBJudgeable
Molecule DecompositionFind the minimum number of edge cuts on a tree needed to isolate a connected subtree of exactly M nodes.Medium6TreeDynamic programming+1No attempts yet2s128 MBJudgeable
Work ProcessGiven a tree of supervisors, compute the tree height and the maximum number of nodes removable while keeping tasks completable within that same height using limited workers per time slot.Medium6TreeGreedy+1No attempts yet2s128 MBJudgeable
Apple TreeGiven a DFS 0/1 traversal string of a tree and two marked positions, find the smallest subtree (by matching visit/return indices) that contains both marked vertices.Medium6TreeStack+1No attempts yet2s128 MBJudgeable
Find Direct SupervisorsGiven employees with salary and tenure, build a supervisor hierarchy by nearest dominating employee and answer queries for direct supervisor and subtree subordinate counts.Medium6SortingTree+1No attempts yet2s128 MBJudgeable
Distances Between Leaf VerticesGiven consecutive-leaf distances of an inorder-numbered binary tree, compute the distance between two arbitrary leaves using a sparse-table style max-range query derived from LCA depth relations.Medium6TreeSegment tree+1No attempts yet2s128 MBJudgeable
Mirror-Symmetric Tree GraphDecide whether a given connected graph can be formed by gluing a rooted tree to its mirrored copy at every non-root leaf.Medium6GraphTree+1No attempts yet1s128 MBJudgeable
Social Network ServiceGiven a friendship tree, find the minimum dominating set size so every non-selected person has all neighbors selected.Medium6TreeDynamic programming+1No attempts yet3s256 MBJudgeable
Hanging MonkeysParse a nested bracket string representing a binary vine structure and compute the minimum monkeys needed so every split has equal counts on both sides.Medium6RecursionString+2No attempts yet1s128 MBJudgeable
Salary Management at a Car FactoryGiven a company tree with salary updates that add a value to all subordinates of a node and queries for a single employee's current salary, answer efficiently using an Euler tour and a range-update point-query structure.Medium6TreePrefix sum+1No attempts yet1s256 MBJudgeable
Binary Search TreeSimulate BST insertion of a permutation and output the running total of comparison steps after each insertion, efficiently for up to 300000 elements.Medium6TreeBinary search+1No attempts yet1s128 MBJudgeable
Complete Binary TreeFill a complete binary tree of level N with numbers 1 to 2^N-1 so each internal node's left/right subtree sums differ by exactly 2^D, then output preorder.Medium6RecursionTree+2No attempts yet1s128 MBJudgeable
Tournament Rank RangeGiven a single-elimination bracket's match winners, determine each queried player's best possible and worst possible final ranking consistent with the known beat relations.Medium6TreeDFS+1No attempts yet1s128 MBJudgeable
Fair DistributionGiven a tree of farmers with equal initial money and required amounts, find the minimum number of edge transactions, in valid order, to make everyone reach their requirement.Medium6TreeGreedy+1No attempts yet1s128 MBJudgeable
Company RestructuringGiven a rooted tree where reporting edges may only be rewired within original parent-child-sibling triples, output a new tree with at most 2 children per node and at most one higher-IQ child than its manager.Medium6TreeGreedy+1No attempts yet1s128 MBJudgeable
Road NetworkFor a tree with weighted edges, answer many queries asking for the minimum and maximum edge weight on the path between two given nodes.Medium6TreeBinary search+1No attempts yet1s256 MBJudgeable
ONEFind the minimum fuel a plough starting at a fixed node needs to traverse every edge of a weighted tree at least once, ending anywhere.Medium6TreeDFS+2No attempts yet1s128 MBJudgeable
MessengersGiven a tree with per-city messenger costs, compute for every city the minimum time to relay a message to the root via edge lengths and messenger switching costs.Medium6TreeDynamic programming+1No attempts yet1s128 MBJudgeable
MinistryParse a nested ternary-tree encoding of an organization and, using tree canonicalization/hashing, count structurally distinct subtrees grouped by depth.Medium6TreeRecursion+1No attempts yet2s128 MBJudgeable
Fenwick TreeGiven an array, find the minimum number of element changes so that the array equals its own Fenwick (BIT) prefix-sum tree.Medium6MathTree+1No attempts yet3s256 MBJudgeable
Common Subexpression EliminationCompress a labeled binary expression tree into a minimal DAG by merging identical subexpressions and print it with backreference numbers to earlier nodes.Medium6Hash mapTree+2No attempts yet1s128 MBJudgeable
Moving to NurembergGiven a weighted tree and visit frequencies at some nodes, find the node minimizing total weighted round-trip distance and list all optimal nodes.Medium6TreeDFS+1No attempts yet1s128 MBJudgeable
MobileGiven a mobile's arm structure and pivot distances, find the smallest integer weights, with a named weight at least w, that keep every arm balanced.Medium6TreeMath+2No attempts yet1s128 MBJudgeable
Knockout TournamentGiven knockout tournament results, find the best and worst possible rank each queried player could hold under a transitive beat relation.Medium6TreeDFS+2No attempts yet1s128 MBJudgeable
Marbles on a TreeGiven a rooted tree where each vertex has a box and the total marbles equal the number of vertices, find the minimum number of moves (along edges) so every box holds exactly one marble.Medium6TreeDFS+2No attempts yet1s128 MBJudgeable
Go Go GoreliansBuild the network by linking each new planet to the nearest existing planet, then find the planet or two adjacent planets that minimize the maximum distance to all others.Medium6GraphTree+2No attempts yet1s128 MBJudgeable
Falling LeavesGiven the leaf-removal stages of a binary search tree, reconstruct the unique tree and print its preorder traversal.Medium6TreeRecursion+2No attempts yet1s128 MBJudgeable
Newton's AppleParse two binary trees from post-order tokens with nil markers, then decide whether one can be turned into the other by swapping left and right children at any nodes.Medium6TreeRecursion+2No attempts yet1s128 MBJudgeable
Off BalanceGiven a 2D grid of digit-labeled blocks, group 4-block pieces, build the support tree, and check each piece's accumulated center of mass against its bottom-column span.Medium6DFSTree+2No attempts yet1s128 MBJudgeable
JuiceGiven a rooted tree with cord capacities and house demands, choose which houses to power so that flow through each cord stays within capacity and the count is maximized.Medium6TreeDFS+2No attempts yet2s128 MBJudgeable
Binary Search TreeGiven the preorder traversal of a binary search tree, print its postorder traversal.Medium6TreeDivide and conquer+2No attempts yet1s256 MBJudgeable
Cellphone Keypad AutocompleteFor each word in a dictionary, compute how many letters a phone keypad must type when unique suffixes are autofilled, then print the average presses.Medium6TrieTree+2No attempts yet1s192 MBJudgeable
Ants ColonyBuild a weighted tree where each new node attaches to an earlier one, then answer distance queries between pairs of nodes.Medium6TreeDFS+2No attempts yet2s128 MBJudgeable
Another CrisisGiven a company tree and a threshold T percent, find the minimum number of leaf workers who must petition so that a petition reaches the root.Medium6TreeDFS+2No attempts yet1s128 MBJudgeable
Bubble MapsGiven a quadtree region name, find the names of its up, down, left, and right neighbors, or <none> if a neighbor falls outside the map.Medium6TreeImplementation+2No attempts yet3s128 MBJudgeable
Nearby CowsOn a tree of N fields with C(i) cows at each field, report for every field the total cows within distance K, where K is at most 20.Medium6TreeDFS+2No attempts yet1s128 MBJudgeable
Visiting CowsGiven a tree with N vertices, choose the largest set of vertices with no two adjacent, which is the maximum independent set on a tree.Medium6TreeDynamic programming+2No attempts yet1s128 MBJudgeable
Chocolate MilkGiven a directed tree with N-1 edges where all flow reaches one sink, list every non-source node that lies on every root-to-sink path.Medium6GraphDFS+2No attempts yet1s128 MBJudgeable
Great Cow GatheringPick a node of a weighted tree with node weights as the gathering point, and minimize the sum of cow count times distance to that node.Medium6TreeDFS+2No attempts yet1s128 MBJudgeable
Time TravelProcess add, pop, and rewind-to-earlier-query operations on a recorded list, printing the last element after each query.Medium6StackTree+2No attempts yet1s128 MBJudgeable
Cell Phone NetworkGiven a tree of N pastures, choose the fewest vertices so that every vertex is chosen or adjacent to a chosen one.Medium6TreeDynamic programming+2No attempts yet1s128 MBJudgeable