May 2024
CodeForces
- Fenwick Tree
- Find the structure and pattern of taking the Fenwick tree to powers
- It involves stars and bars method and combinatorics, counting method.
- Also helpful to have understanding about how binary indexed tree or fenwick trees work.
- Equal XOR Segment
- Related to range xor queries
- Can precompute the xor sums just like prefix sums algorithm.
- Greedy you split into either 2 or 3 segments.
- Division + LCP (Hard Version)
- z-algorithm
- memoization binary search
- Trails (medium)
- dynamic programming
- matrix exponentiation
- Trails (hard)
- Associativity in matrix multiplication. BCBCBC = B(CBCB)C
- matrix multiplication is not commutative.
- Get into format where it is a 2 x 2 matrix
- Exact Neighbors (hard)
- constructive, pattern
- If ai = 0, then you can place rest in zig zag
- They are all distinct can place (1, 2, …, n) in zig zag
- There is no ai ≠ 0 and they are all distinct, place zig zag, but skip at first repeat
- Min-Fund Prison (medium)
- graph theory
- connected components
- Tarjan’s bridge finding algorithm for finding the bridges in undirected graph
- Subset sum problem algorithm, slightly modified to track if a split has happened, can be done with boolean
- Min-Fund Prison (hard)
- reversible knapsack or subset sum dynamic programming algorithm
- Review this one
- Tower Upgrades
- dynamic programming on tree
- preorder tree traversal
- Feeding Elmo
- dynamic programming
- size of arithmetic sequence
- ±1
- 2-SAT problem
- strongly connected components
- Tarjan’s algorithm to find strongly connected components
- directed implication graph
- Engineer Artem
- Equivalent to just having cell be odd and all it’s neighbors even
- Envision a checker board
- Assign first block to be odd, and then determines the rest greedily from that.
- Tensor
- partially ordered sets
- Dilworth’s theorem
- vertex set for a DAG ordered by reachability
- other applications of partially ordered sets
- Set of natural numbers with the relation of divisibility
- Set of strings ordered by substring
- Set of sequences ordered by subsequence
- The largest antichain is equal to the minimum number of chains needed to cover the entire vertex set.
- For this example you can prove that the largest antichain is just a set of two nodes, therefore you only have two chains.
- logic is important to this problem, cause you can have vertex j reach vertex i and they can be the same color or different colors, but the only thing that is actually illegal is that you cannot have vertex j and vertex i be same color and i is unreachable from j.
- The reason the chains work, is because a chain is a totally ordered set, so that means each element in the chain is reachable from earlier elements, or in other words they are comparable.
- This guarantees you will never have two elements of same color but they are in-comparable.
- You can develop a three stack solution to find the two chains. The reason you need three stacks is because sometimes an element can reach both colors.
- You are also iterating from smallest to largest integer because the larger ones reach the smaller
- Set
- bitmasks and binary encoding of sets
- Decision tree problem
- Start with a state of a set S = xxxx, where every element in the set is undecided, and each can be value 0 which represents S does not contain that element or 1 meaning S contains that element. Where the index from the left to right indicates the element value.
- So through the tree you will decide on some elements that S contains, so you could end up in a state like S = xx10, where you have made a decision partially about what S contains.
- From that partial decision, you can use a pattern in the binary encodings to merge constraints and half the constraints at each step, or in other words half the number of T sets that will be used for next iteration.
- It uses the fact that if you disregard the last element, you will notice you have pairs of binary encodings where the prefix are equal, so you can merge those two T sets, cause you only care about the prefix in the next element you consider cause it is a bit at the next position.
- Money Buys Happiness
- Variation of Knapsack problem
- Min Cost Knapsack Problem
- Slight constraint added where the cost cannot exceed some prefix sum of your current amount of money you can have up to some day.
- Solve in dp with O(NM), N = number of items, and M = total weight
- Cutting Game
- Can be solved with techniques involving two pointers and marking what was used
- Treat the rows and columns independently.
- Money Buys Less Happiness Now
- tricky greedy algorithm
- You can kind of think of it by considering the cases mentally
- Use a lazy segment tree with range addition queries
- Add elements and it computes the sums over ranges
- It can return the min or max for the query, I think anything
- Ingenuity-2
- Just have to come up with the simulation
- Must be careful though in doing so.
CodeSprint LA
- Catbus Planning
-
Eulerian paths and circuits
-
undirected graphs
-
Count degree of nodes
-
Even number of nodes with odd degrees in any undirected graph
-
AtCoder
-
MST Query
- Interesting union find algorithm
- Since you have only 10 weight values, you create 10 separate graphs with union find
- Then you perform union find for elements in those 10 graphs
-
Remove Pairs
- minimax algorithm
- recursive dynamic programming with bit manipulation
-
Clique Connect
- Lucked out on this one maybe, but just used a greedy algorithm with minimum spanning tree
-
MST Query
CodeChef
-
Graph Cost
- Not that challenging
- Some form of greedy and suffix computation
-
Milky Dark Chocolate
-
Envious Pile
-
Limit Mex
- max(A[l:r]) + 1 - count(distinct[l:r])
- You want to calculate these sums for each subarray that is the maximum element in the ranges
- Find the nearest element greater than A[i] to the left
- Find the nearest element greater than A[i] to the right
- Perform two monotonic stack sweeps in different directions to compute these.
- This will give you the number of times A[i] is the maximum value. So now you can sum that up
- Still need to compute the total sum of distinct elements in each subarray range.
- consider the value x = 5, the first time you see it in the array, you now know that it can be the distinct element for potentially N * (N + 1) / 2 subarrays so you subtract that from answer. Because you are subtracting count(distinct[l:r])
- If you see x again so you see at index = 3 and index = 7, then you know that it is not a distinct for the range from [4, 6], so you want to count the number of subarrays in that range, and add that to the answer.
-
Prison Escape
- multisource dikjstra from the outside of a grid and moving inwards
- calculates the minimum number of distance or in this case number of guards that must be passed to reach the outside of the grid
- It finds the cell that has the maximum distance to escape
-
Chef and Bit Tree
- You can simplify the problem if you know an identity relating addition to bitwise operation x + y = x & y + 2*(x^y)
- Once you do that you have a property of pigeonhole principle
- So you will never have to explore a path longer than 1000
- So it can be solved almost with brute force algorithm that finds the LCA, by using two pointers and moving the one at a lower depth in the tree upwards.
- As it climbs the tree to find LCA, it tracks what values have been seen with a marked array
- If two values seen in a path, which will happen before 1000, because only 1000 distinct elements possible. Then the answer is 0 because you are able to get the problem to a minimize of x ^ y, and yeah you can minimize if x = y cause it is 0.
- Else you use another important property of the following problem
- Given an array of elements the minimum xor of a pair will come from two adjacent integers.
-
Permutation Cycle Queries
- compute multiple prefix sums
- Avoid division with observation that you can compute prefix product and suffix products
-
Mex Path
- Hard one but you need to construct a graph with fewer edges to run dijkstra algorithm to find shortest path
- create forward edges from start node to every other node using mex for edge weight
- create forward edges from every other node to end node.
- create backward edge between adjacent elements with edge weight = 0, this correct for overshooting
- creates these edges from the last time a value was seen in array to the next time, you can create an edge of weight to connect just before value seen and set the edge weight to that value.
- Get’s it down to 4N edges and now can perform traditional Dijkstra
LeetCode
- Special Array II
- good practice for offline query algorithm and line sweep
- Also need to use a python list and know which queries are still within the range.
- Sum of Digit Differences of All Pairs
- Easy implementation, just need to understand problem.
- Find Number of Ways to Reach the K-th Stair
- dynamic programming with Counter
- k is large, but the jumps will increase 2^x, so actually the number of states is smaller than it appears
- Block Placement Queries
- Use a max segment tree with coordinate compression
- If you draw it out you can see what to do
- It does need sorted list to keep track of obstacle locations
- And you can query given some obstacle position, and find the maximum size of a contiguous segment
- There are ghost obstacles that have no been placed yet but need to be included in the segment tree so they can be added.
- Use binary search to find the nearest obstacle and then find distance to that obstacle and and query the max segment tree for anything to the left of that obstacle
- Student Attendance Record II
- dynamic programming with simple transitions if you add A L or P to the string
- But you can only add them under certain conditions etc. Just need to follow the rules
- K-th Smallest Prime Fraction
- binary search for fraction from 0 to 1.0 and count number of fractions less than each possible candidate.
- O(n^2) to calculate the number of elements fractions that are less than some target
- Find the Minimum Cost Array Permutation
- dp bitmask where you are minimizing the score
- And you always start from 0 because you want the lexicographically smallest and it is circular
- And you also perform the dp algorithm with a backtracking pointer
- Distribute Coins in Binary Tree
- dfs post order traversal of the tree
- determine the number of coins you need to travel up the tree and sometimes negative if it needs coins
- and the number of coins that much move on this edge is absolute value sum of the excess and shortage
- Score After Flipping Matrix
- greedy algorithm, where you want to always flip all the bits along a row if it doesn’t start with a 1
- Then you flip if the column count has more 0s then 1s
- Find the Maximum Node Sum of Node Values 1.
Problems
- Another Longest Increasing Subsequence Problem
- 2D LIS or LIS on pairs
- Creative algorithm using this sorting with staircase can solve it in O(n(logn)^2) time
- This algorithm visualized is like a bunch of disjoint staircases that never intersect each other. And you are always trying to minimize the area under the staircases.
Comments
Post a Comment