Editorial for some of the new CSES tasks. Tasks that are trivial or too similar to already existing tasks are not included.
Every time I solve a new nontrivial task, I will add it here.
NOTE: ONLY READ THE SOLUTIONS IF YOU ARE COMPLETELY STUCK AND OUT OF IDEAS. CSES tasks are the kinds of tasks you can solve at a random time by random chance. You might read a task today and solve it next week. Or next month. Or next 3 months. So read at your own risk.
Sorting & Searching
For each value $$$x$$$, we can include $$$0$$$ or $$$1$$$. If $$$f(x)$$$ is the number of times $$$x$$$ appears in the array, Then there are $$$f(x) + 1$$$ ways to pick $$$0$$$ or $$$1$$$ occurrences of $$$x$$$. Since every value is independent of every other values, we will take the product of $$$f(x) + 1$$$ over all $$$x$$$. This can be done with std::map or sorting.
Dynamic Programming
Let $$$L_i$$$ be the nearest greater element on the left, and $$$R_i$$$ be the nearest greater element on the right. These can be calculated in $$$\mathcal{O}(n)$$$ with monotonic stack.
From the value $$$i$$$ we can go to any value in $$$[L_i + 1, R_i - 1]$$$ that's strictly smaller than $$$h_i$$$. So we will calculate the DP in increasing order of $$$h_i$$$. The formula will be:
We can calculate this with a segment tree. We also have to take care of duplicates by calculating them at the same time and then updating the segment tree.
There are plenty of solutions that are straight-forward greedy, but I will describe a nice solution that uses DP.
The most obvious DP is $$$dp(i, j)$$$ being the lexicographically smallest string if you start in the cell $$$(i, j)$$$. Obviously, $$$dp(i, j) = A_{i,j} + min(dp(i+1, j), dp(i, j+1))$$$. Unfortunately, this is $$$\mathcal{O}(n^3)$$$, since each string can be of length $$$n$$$. We need to somehow find a way to compare strings without storing them. The way to fix this is: compression!
Now instead of calculating $$$dp(i, j)$$$, we will calculate $$$ord(i, j)$$$, which will just be an integer satisfying the following condition:
for all $(i_1, j_1), (i_2, j_2)$ in the same diagonal.
To calculate some diagonal, we will take each cell $$$(i, j)$$$ and sort them according to $$$(A_{i,j}, min(ord(i+1,j), ord(i,j+1))$$$. $$$ord(i, j)$$$ will simply be the position of $$$(i, j)$$$ according to the sort.
This is $$$\mathcal{O}(n^2 \log n)$$$ using std::sort, and it gets TLE. However the log can be removed using radix sort.
Range Queries
Let $$$P_i$$$ be the nearest greater element on the right. This can be calculated with monotonic stack. Now the query becomes: "How many times can you perform the assignment $$$l = P_l$$$ while $$$l \le r$$$?". This can be solved with binary lifting.
This can be solved using merge sort tree. In each node of the segment tree, we will store all the elements in the range in nondecreasing order.
For each query, we will decompose it into $$$\mathcal{O}(\log n)$$$ nodes, and each node, we will count the number of values between $$$c$$$ and $$$d$$$ in $$$\mathcal{O}(\log n)$$$ using binary search. This way, we can answer each query in $$$\mathcal{O}(\log^2 n)$$$, which is fast enough.
Let $$$S_i$$$ be the nearest equal element on the right, or $$$∞$$$. If there's an $$$i$$$ in $$$[l, r]$$$ such that $$$P_i \le r$$$, then $$$a_i = a_{P_i}$$$. That means not all values in $$$[l, r]$$$ are distinct. To check if such $$$i$$$ exists in $$$[l, r]$$$, check the minimum $$$P_i$$$. This can be done with a segment tree.
In each update, $$$\mathcal{O}(1)$$$ values change, so it can done in $$$\mathcal{O}(\log n)$$$ per query.
Mathematics
The average prime gap is $$$\mathcal{O}(\log n)$$$. So the trivial solution actually works in $$$\mathcal{O}(\sqrt{n} \log n)$$$. It can also be done in $$$\mathcal{O}(\log n)$$$ using randomized primality checks.
Imagine a functional graph with $$$n$$$ edges of the form $$$i \rightarrow p_i$$$. Let $$$L_1, L_2, ..., L_k$$$. The answer will be LCM(L_1, L_2, ..., L_k). This can be calculated by factorizing in $$$\mathcal{O}(n \sqrt{n})$$$ or $$$\mathcal{O}(n \log n)$$$ with sieve.
Sliding Window Problems
This can be done with monotonic queue, which allows adding an element at the back, removing the element from the front, and extracting the minimum. https://cp-algorithms.com/data_structures/stack_queue_modification.html#queue-modification-method-1
This can be done with a std::map to maintain the frequency of each value.
This can be done with a std::map to maintain the frequency of each value, as we as a std::set containing (frequency, values) pairs.
This can be done with an array to maintain the frequency of each value (since only values $$$\le k$$$ are relevant for th mex), as well as a std::set of excluded values.
This can be done by maintaining the number of inversions and an ordered set.
When adding a new element $$$x$$$, we will add the number of elements greater than $$$x$$$ to the inversion counter (since $$$x$$$ is at the end of the subarray).
When removing an element $$$x$$$, we will subtract the number of elements less than $$$x$$$ to the inversion counter (since $$$x$$$ is at the start of the subarray).
Distinct values, mode, MEX, and inversions can all be solved using a segment tree and coordinate compression.
Interactive Problems
We can use mergesort. This uses $$$n \log n$$$ queries.
Let's query chair $$$1$$$ and chair $$$N$$$. If they're equal, then we have found a solution. Otherwise, we can solve using binary search.
Let's query chair $$$x = \frac{N+1}{2}$$$. If $$$x$$$ is odd and chair $$$1$$$ is equal to chair $$$x$$$, we can guarantee a solution in $$$[x, n]$$$. Same can be said if $$$x$$$ is even and chair $$$1$$$ is not equal to chair $$$x$$$. Otherwise, there always exists a solution in $$$[1, x]$$$.
This solution uses exactly $$$2 + \lceil \log_2 n \rceil$$$ queries, which is at most $$$20$$$.
Advanced Graph Problems
There exists a path between $$$u$$$ and $$$v$$$ of length $$$w$$$ iff the shortest path between $$$u$$$ and $$$v$$$ with the same parity $$$w' \le w$$$.
Construct a graph with $$$2N$$$ nodes, each node representing a pair (node, parity of path length). For each edge $$$(u, v)$$$ we will add undirected edges between $$$(u, 0), (v, 1)$$$, and $$$(u, 1), (v, 0)$$$.
Now for a query $$$(u, v, w)$$$, we have to check if the shortest path between $$$(u, 0)$$$ and $$$(v, w \mod 2)$$$ has length less than or equal to $$$w$$$. These distances can be precalculated in $$$\mathcal{O}(n (n + m))$$$ with BFS.
Additional Problems
For each $$$i$$$, let $$$P_i$$$ be the number of $$$j$$$ such that $$$j \lt i$$$ and $$$x_j \gt x_i$$$. The answer will be the maximum $$$P_i$$$, since during each round, $$$P_i$$$ decreases by $$$1$$$ for each $$$P_i \gt 0$$$.
Let's consider each prime factor of $$$k$$$ separately.
Let's say that we want to calculate the number of ways to place the prime $$$p$$$. Let's say the number of times $$$p$$$ appears in the factorization of $$$a_i$$$ is $$$c_i$$$. The condition from the statement is equivalent to $$$\max(c_i, c_{i+1}) = X$$$, where $$$X$$$ is the number of times $$$p$$$ appears in the factorization of $$$k$$$.
Let $$$dp_p(n)$$$ be the number of arrays $$$c$$$ of length $$$n$$$ such that $$$\max(c_i, c_{i+1}) = X$$$. There are two cases:
$$$c_n = X$$$
$$$0 ≤ c_n \lt X, c_{n-1} = X$$$
So $$$dp_p(n) = dp_p(n-1) + dp_p(n-2) \cdot X$$$. $$$dp_p(n)$$$ can be calculated by raising a matrix to the $$$n$$$-th power in $$$mathcal{O}(\log n)$$$.
We can calculate this for each prime and multiply them to get the final answer, since the primes are independent of each other.
Subtract $$$a$$$ from each value in the array. Now we must count the number of subsets with sum $$$0$$$. This can be done easily with DP.
$$$dp(i, sum)$$$ is the number of subsets of $$$x_1, x_2, ..., x_i$$$ that add up to 0. Obviously $$$dp(i, sum) = dp(i-1, sum) + dp(i-1, sum - x_i)$$$.
We can handle negative value sums by sorting the array decreasingly so that the sum never goes below $$$0$$$. The final answer is $$$dp(n, 0)$$$.
We can do binary search on answer.
To check if the answer is at least $$$x$$$, subtract $$$x$$$ from each value in the array. Now we have to choose two prefixes that add up to at least $$$0$$$. We greedily take the biggest prefix sum of $$$a$$$ and $$$b$$$.
Also, $$$x$$$ doesn't have to be an integer.
Additional Problems II
We will calculate $$$dp(k)$$$, which is the number of subsets with GCD being $$$k$$$.
$$$dp(k)$$$ will be all the subsets of elements that are divisible by $$$k$$$, subtracting the subsets that have GCD being greater than $$$k$$$, i.e. $$$2k, 3k$$$, so on. Therefore:
This seems like it's $$$\mathcal{O}(n^2)$$$ but in reality it's $$$\mathcal{O}(n \log n)$$$.









The problem statement of Mountain Range is ambiguous imo. How do you go from mountain a to b when the segments lying in between them are not monotonically decreasing ?
Someone pls explain the problem statement
If $$$h = [5,1,4,2,3]$$$ you can go from the first mountain to any other mountain.
So its a subsequence thing, it makes sense now, thanks :) My Solution
hi! why you use lazy?
Its a generic template for segment trees.
The problem still does not make sense to me. Can I travel in any direction? If no, then why is the answer to test case number 4 equal to 200000. If yes, then why is the answer to test case number 1 not equal to 10?
@Eyes_on_me Sul_A.
You can go in either direction.
Could you please describe how we can move from first mountain to any other? Best I can think is: 5->4->3->2. Then I can not visit 1 because 4 comes in between 2 and 1
going from 5 to every mountain means that its possible to visit them, not necessarily in the same path. You can go from 5 to 1 directly. Also answer for 1st testcase is 5 because you can choose the path : 40 -> 35 -> 20 -> 17 -> 15
It cannot be 10 as if you choose to start at 40 (the max element of the array), you'll have to jump it after some moves to traverse all elements which is not possible, and if you don't choose to start at 40, you can never attain it as its the max element.
I'm sorry if I misunderstand, but if I can take more than one paths (e.g.
You can go from 5 to 1 directly) i.e. I am allowed to "reset", then can I not always visit every mountain if I just start at the largest mountain? I mean I can 'directly' go to any other mountain from the tallest mountain since it is guaranteed that I will never face a larger obstacleNo, you can't reset. In the comment he meant that its possible to visit every mountain through some path. Essentially there are 2 paths possible from mountain 5 :: 5 -> 1 and 5 -> 4 -> 3 -> 2. in the problem you have to find the longest path which is the second one.
Ah got it, thanks a lot mate
Basically u move from mountain a to b where h[a] > h[b] and everything between must be in decreasing order of height from a to b (b can be in either direction of a) now again you continue your journey from b to some c such that the
same above conditionsalso apply for going from b to c ... go until you can and find the max no. of mountain ranges in that range !NOTE : 5 4 6 1 you cannot go from 5 to 1 directly (6 is in between) here max answer is 3 (path -> 6 -> 5 -> 4)
input 10 3 46 77 16 59 32 22 41 87 89
output 7
path 89 -> 87 -> 77 -> 59 -> 41 -> 32 -> 22
But take care u cannot move from 3 -> 1 or 2 -> 1 bcz 4 is in between
Range Interval Queries can be solved in O(NlogN) offline.
Suppose we have have a function f(i, l, r) that calculates how many elements are there with index <= i and value in [l, r]. Now for each query (a, b, c, d) we add two events:
at a-1 remove f(a-1, c, d)
at b add f(b, c, d)
f(i, l, r) can be calculated in logN with basic fenwick tree for sum.
Hi! I implemented it but it gives TLE. Here is my code https://cses.fi/paste/536c8249fac45604c645ec/
I also have the same problem, even with fenwick tree. I dont know how that's possible, as I have used this same solution for other problems before.
My solution with fenwick tree works in 0.31 seconds. Could you share your solution? Here's mine: https://cses.fi/paste/4050cb3f348da766c6703f/.
Here you go
I looked at your code, and it doesn't seem like it should TLE. Maybe there's some constant factor issue?
I solved this task, thanks beaten_by_ai your code helped to me.
good luck on IOI!
You're welcome, glad it helped :)
I'm honored, but our TST isn't done yet. Thanks anyways!
Ordered set also works. Complexity is same, just simpler to implement.
My code
You can solve Sliding Window Or by maintaining counts of each bit. But my solution required using SIMD intrinsics + pragmas to pass.
I solved it today in linear time actually ;)
You can solve it in O(n) using the two stacks trick (same trick can be applied to any associative operation).
and what is two stacks trick? any reference?
Section "Segment with small spread"
Sliding Window: Handling Non-Invertible Operators
Is slope trick similar to two stacks trick?
You don't actually need pragmas just eliminate your if statements
https://cses.fi/paste/2e4f33786d1cfccac4a966/
About the solution of next prime, it's not correct to use average prime gap to estimate complexity since the test cases are not necessarily generated randomly, and the upper bound of prime gap should be used. And I doubt Miller-Rabin test can be run in just one log factor. the implementation from KACTL seems to have 2~3 log factors depending on whether you think size of $$$A$$$ as constant.
First problem in the Interactive Problems section requires log n queries instead of n log n. Imo binary search would be much easier to implement in this problem.
How do you solve Hidden Permutation using binary search?
I am sorry, mixed it with another problem
Build the answer by prefix.
Consider the following algorithm:
Goal: Label the prefix $$$[1, i]$$$ with labels $$$[1, i]$$$, while preserving the relative ordering of the elements. The answer will be complete when we successfully label the entire prefix $$$[1, n]$$$.
Base Case:
$$$a[1] = 1$$$
Inductive Step:
Assume we have already labeled the prefix $$$[1, i - 1]$$$ using labels from $$$[1, i - 1]$$$, such that the relative ordering with respect to the actual permutation is preserved for all indices $$$j, k \lt i$$$.
Now we want to extend the labeling to include the $$$i$$$th index. One way to do this is via binary search: We need to find the leftmost number $$$k \in [1, i]$$$ such that $$$a[i] \lt k$$$.
Then we set $$$a[i] = k$$$, and increment all existing labels from the prefix $$$[1, i - 1]$$$ that are greater than or equal to $$$k$$$.
If no such $$$k$$$ exists, then we set $$$a[i] = i$$$.
This step takes $$$\log(i)$$$ queries.
Reference Code: https://cses.fi/paste/b4b9437e5ed90652ca32d9/
If you allow $$$L_i$$$ and $$$R_i$$$ to be elements equal to $$$h_i$$$ (instead of strictly less/greater), you don't have to account for duplicates.
Submission
You must use
stable_sortinstead ofsortfor C++Why does
std::sortnot work?Edit: With the help of PeruvianCartel's comment and some independent reseach I did on the day itself, it seems as straightforward as STL's implementation of
std::sortuses quick sort whereasstd::stable_sortuses merge sort.for anyone doesn't know,
stable sort, which is basically merge sort, only have to perform a pretty low number of comparisons. It's not optimal, but it's there (the theoretical optimal number of comparison to sort an array of 1000 elements is 8530, and merge sort accomplish that in 8977, while quick sort accomplish that in around 11000).Binary lifting is not needed in "Visible Building Queries", just answer queries offline and binary search on the stack.
https://cses.fi/paste/92acd924a955ed05c4ba93/
orz
orz
Mountain Range can be solved without segment tree, here's my submission with comments Submission
could you please elaborate your solution.
Any hints for Minimal Grid Path, string hashing is useless here!
I think you already knew that if right cell is 'A' below one is 'B' then you must only go right cuz that only way to get lexicographically minimum walk from there you can do some form of graph traversal like bfs to construct optimum walk try it
what about grid like below?
AAAD
BACA
CBCA
I don't think greedy works here.
like from your (1,1) the only possible position is to go (1,2) rigth cuz the (2, 1) is B, then from that(1, 2) it could either go right or down right cuz that both 'A' then I add both position it to my queue then consider the next level it could either be 'D', 'C' or 'B' that extend from the past level then I extend to 'B' and so on like construct it by level, btw the code got accepted if you got counter test that you suspect I'll try
will not it give TLE?
suppose everything is just A
I did try the 3000*3000 grid with only 'A' now and it fine, but like don't we got like only 3000^2 node(cell) at most I don't think the bfs will gives TLE here my submission:https://cses.fi/paste/a48220f9100d7c7ec45824/
Okay, so you're marking visited as well, I thought you're not
if you iterate diagonal by diagonal then you can look at the cells in the next diagonal and only consider those with minimum value. there are at most n cells in a diagonal so the code runs in O(n^2)
looks like greedy , but i wonder why it is marked as Dp in the problemset
Bfs is correct on this one (You remove all path that is not optimal straight away)
I could do it within time limit by simple bfs and maintaining a visited array.
My BinLift+StringHashing gave MLE . Then saw that we can find the optimal path using level order BFS
It's simply a BFS starting at node (0, 0)
BFS Solution
can someone give me segment tree(doesnt matter if it is lazy or regular) problems that are on codeforces?
https://cp-algorithms.com/data_structures/segment_tree.html
tysm
bro i need a paper on graphs of dsa
(cause im researching on neural networks since last week and my goal is to optimize it)
For the Range Interval Queries, I'm struggling to find out why my implementation of Merge Sort Tree gets TLE
https://cses.fi/paste/f21d39c5ee195b1bc607b8/
In fact, I solved it using Wavelet Tree and after I tried submitting the official solution from CSES that uses Merge Sort Tree and even their code gets TLE as well
Any thoughts?
nlog^2 won't pass due to cses servers
https://cses.fi/paste/a08d91d000cd0bd0c6a48a/, its passes:D
Same here, Even tried Fractional Cascade for log(n) per query but getting TLE
Merge Sort Tree: https://cses.fi/paste/b511af4431dcd62fc69482/
With Fractional Cascade: https://cses.fi/paste/08fc0fb0453775d1c6a112/
Mountain Range I don't use segment tree. This is my code https://cses.fi/paste/902973a8389f6ae2c6bd6a/
can u explain a little?
I use monotonic stack to connect graph and then use dp top down to find longest path on DAG
Got it, thanks!
3 46 77 16 59 32 22 41 87 89
can you explain how the answer here is 7
Condition mentioned in the question is the criteria for making jumps i.e. gliding from mountain a to mountain b, You can make a jump from 89 to any other element in the array since 89 is greater than every other element as well as greater than all elements in between itself and any other element.
So, the path you can consider is the following:
89 -> 87 -> 77 -> 59 -> 41 -> 32 -> 22
Path length is 7. Therefore, answer is 7.
Can someone explain me how do we use segment tree for finding mode in a given interval?
i think it can be solved using segment tree beats, it will help: https://www.youtube.com/watch?v=NwkO73jGSPA
can anyone pls share their Binary lifting solution of Visible building queries (from range queries), I am facing TLE on one test case,
my code : https://cses.fi/paste/079399dd9980b4b8c9ea9c/
try to do it without binary search, with binary search your solution works $$$O(q*log(n)^2)$$$, which will not pass.
if you will not be able to do it, here is your updated code https://cses.fi/paste/00b50365d75e4995ca7806/, and now complexity is $$$O(q*log(n))$$$.
This is my solution that uses binary lifting and then a binary search .
https://cses.fi/paste/00db844c15279cbecc2f4f/
The reason I believe your code is not working because your you are accessing the elements of your DP column wise which leads to a lot of cache misses for large test cases, if you transpose your DP matrix, your solution should work
Thanks I will have a look, i completely forgot this thing it has happened with me before.
Thank you very much!
can anyone help me with Sliding Window Advertisement and Xor Pyramid Row.
For xor pyramid row, look at the case where k=2^something. Then, for the general case, just write k as sum of powers of 2.
I'm very bad with bits, can you elaborate more?
Sorry, I meant the case where n-k is a power of 2.
We have to lift the bottom row k times. Let's say n-k=1 and look at an example:
Now let's take a look at n-k=2:
We can see that if n-k is a power of 2, we have:
We can proof this inductively. n-k=1 is a base case. Now let's proof it for
n-k = x > 1Just write n-k as a sum of powers of 2. We can do this using the bits.
Thanks, it helped!
Can anyone tell me the correct problem statement of Mountain Range I am not able to understand it
There are n mountains in a row, each with a specific height. You can start from any mountain, you can go from mountain a to mountain b if height a is strictly greater than height b and all of mountains in that range([a, a+1, a+2, ..., b] you can go to b if h[a] > max(h[a+1], h[a+2], ... h[b] same thing if a > b). and now the question is what is the maximum number of mountains you can visit on your route?
consider this array:
[20, 15, 17, 35, 25, 40, 12, 19, 13, 12], if you start from 5th mountain you cant go, but if you start from 8 mountain you can go to 7, 9 and 10 mountains.For Distinct Values Subsequences, remember to subtract 1 to account for the empty subsequence
Here is my solution for the Mountain Range, it's a simple solution (no segment tree/fenwik tree/any new sorting techniques). just start from the highest mountain and run a dp such that i'th index is updated using the nearest higher mountain at left and right of it(if they exist).
I don't seem to understand the Mountain Range statement quite well.
Could anyone explain to me this test case from cses:
array: [3 46 77 16 59 32 22 41 87 89]
answer should be 7
But I think the answer should be 6: [77 16 59 32 22 41]
You can go both left and right. So the path is 89, 87, 77, 59, 41, 32,22
it make sense, thank you !
why we can't jump from the last element 89 to first one 3 , as all the elements b/w them are lesser than 89 , i'm confused !
yes you can jump from 89 to 3, but the elements in between are not counted in the answer, only 89 and 3 are visited, after this you should look for the next jump.
basically you can jump in any direction as long as the condition is met.
That's what I didn't get in the beginning.
Got it! thanks
2109D - D/D/D
I have not seen anyone posting construction section, here are my solutions to some of them (couldn't solve last 3)
Inverse Inversions
If we have a sorted permutation, moving an element from index $$$j$$$ to $$$i$$$ (where $$$j \gt i$$$) increases the number of inversions by $$$j - i$$$ for example if we have $$$n=5$$$ ($$$p=[1, 2,3,4,5]$$$) The move we can do that maximizes the inversions is moving $$$5$$$ to beginning of the permutation which makes it $$$[5, 1, 2, 3, 4]$$$, here the number of inversions is $$$5 - 1 = 4$$$. The next maximum move is to move the $$$4$$$ to the $$$p_2$$$, which makes $$$p=[5, 4, 1, 2, 3]$$$ and the number of inversions equal to $$$5 - 1 + 4 - 2 = 6$$$
So the solution goes as following,
The maximum move at index $$$i$$$ is to move $$$n - i + 1$$$ to $$$a_i$$$
While we can make the maximum move without having the number of inversions exceeding $$$k$$$ then we do it.
Otherwise, we insert $$$k - inversions + 1$$$ at index $$$i$$$ (which makes the number of inversions equal to $$$k$$$) and add the rest of the numbers in order.
Monotone Subsequences
The optimal answer is to print decreasing groups of size $$$k$$$ where each element in a group is smaller than any element in the next group, in other words we print the following:
The guarantees that there are no decreasing subsequences of length larger than $k$, now we need to confirm that there are no increasing subsequences of length larger than $$$k$$$, since a group is of size $$$k$$$ we can have at most $$$k$$$ groups, if we printed them and there are still more numbers to printed this means that the length of the longest increasing subsequence will exceed $$$k$$$, so we print ``IMPOSSIBLE'' if $$$k^2 \lt n$$$.
Third Permutation
If we assign every element to the first available index we will match at least $$$n - 2$$$ elements.
For $$$n = 3$$$ there is always a way to match them.
We match the first $$$n - 3$$$ elements greedily by placing every element in the first available index (this can be done using a set by checking the first 3 elements in the set, one of them has to be valid)
For the remaining 3 elements, we try all possible permutations of them.
Of course if $$$n \lt 3$$$ there is no solution.
Permutation Prime Sums
We iterate from the largest to smallest number, for each number $$$i$$$ we check primes starting from $$$2 \cdot i$$$, if we have a number $$$j$$$ such that $$$i + j = prime$$$ we mark them as used and add both of them to the answer (add $$$(i, j)$$$ and $$$(j, i)$$$) we can use a set or frequency to check for the existence of $$$j$$$ quickly, if $$$j$$$ does not exist, we try a smaller prime.
There is always a solution and the number of times we iterate over the primes will be small (can't find a proof for this..., I'm guessing because the prime gaps are usually small we will always reduce $$$j$$$ by a small number like $$$2$$$)
Chess Tournament
We iterate over all players if the player wants to play $$$x$$$ matches we choose the $$$x$$$ players with the largest number of matches remaining, to do this we can use a priority queue pop the top $$$x$$$ players and store them in the answer, if one of them can't play anymore then there is no solution, we push them back to priority queue after decrementing the matches they have remaining by one.
I would be really thankful if someone tell me how to solve Distinct Sums Grid
Not sure if I'm misunderstanding the problem statement but for Third Permutation wouldn't the code break on this test case?:
Although I think the idea could be adjusted to assign the first n-4 greedily instead, which would work.
Did you just hack CSES's solution as well?
I tried all possible input for $$$n \le 7$$$, assigning greedily till $$$n - 4$$$ worked in all tests.
Can anyone show me how to solve Hidden Permutation using merge sort?
please provide the full solution of Hidden Permutation
Hi, I was trying to solve the problem Advanced Graph — Course schedule 2 : https://cses.fi/problemset/task/1757,
My approach is follows :
If we have to do course "a" before course "b", then add a edge from b->a in the graph .
Now in this graph run DFS for each component and keep a track of the minimum node value you have in the subtree.
Now, sort the adj list based on the minimum node value in each subtree, so that If there a multiple ways to do projects "i" then I greedily choose the branch that would lead to do the next-smallest option available as the question requires
Now once, I have sorted the adj_list , I run a dfs and push the node in the result vector once you have traverse all of it's children , this is done in dfs2
I couldn't figure what is wrong in my code, it fails one test-case on CSES, also I believe the run time is O(n+nlogm), so it should pass given the constraints but it gives TLE on one test case
My code link : https://cses.fi/paste/3febffc363f54010ceed11/
In the Range Interval Queries problem, I tried merge sort tree with fractional cascading to make the queries in 2 * log(n) but it still gives TLE. Here is my code
Range Interval Queries can also be solved using Binary Indexed Tree.
#elements with index in range [l, r]
= #elements in the whole array
- #element in the range [1, l — 1]
- #element in the range [r+1, n]
Each item on the right of the equation can be calculated separately with sorting of the queries.
For mountain range for every element you can come on it from either the nearest element on left greater than it or the nearest element on right that is greater than it so we take max of these two this can be implemented in o(n) so a better solution ig
Isn't the solution to the Minimal Grid Path problem derivable using BFS? Writing a DP solution for it feels quite unintuitive.
dp is pretty intuitive for it (because of similar problems like Grid Paths I) but it fails because of O(n) string comparison. bfs is the solution as you noticed.
Can someone please give a detailed explanation of what SegTree node is going to store in distinct value queries 2 ? if SegTree is going to be of minimum Si for an interval , then how will we manage updates fast ?
Sure, let $$$\text{next}[i]$$$ be the index of the next occurence of $$$a[i]$$$. Then do you see how ensuring that $$$\min({\text{next}[l]\dots \text{next}[r]}) \gt r$$$ ensures that the next occurence of any element in $$$[l,r]$$$ occurs after $$$r$$$, thus ensuring that $$$a[l]\dots a[r]$$$ contains distinct elements? The solution is to maintain $$$\text{next}[i]$$$ with a segment tree (to allow for efficient $$$\min$$$ queries), dynamically updating the two places it changes on every update.
Implementation: https://cses.fi/paste/d2e6d3cc7abc11eec468c5/
Hey, I am using the same approach but I am getting TLE. Could you find what's wrong with my implementation?
Should I use the segtree implementation that takes $$$O(2n)$$$ space (like you did)?
Stop using
std::unordered_map. Use coordinate compression like I did.I've tried that too. This still gave me a TLE.
Alright, let me have a closer look. Hold on
Alright, I had a closer look. You're still using
std::unordered_mapfor coordinate compression itself. Tip: never use that. Ever. Try coordinate compressing using thebuf+std::unique+std::lower_boundtrick (if you haven't seen this yet, it's worth checking out)Edit: I just saw that you are indeed using that trick. Nice. Just remove the map and use
std::lower_boundinstead and that should fix it.Making this change got it accepted. Thanks for the tip. I was aware about hashing collisions that can lead to $$$O(n)$$$ but I guess I underestimated it :|
Oh yeah, unordered map is basically a scam. No problem!
For "Visible Building Queries". I think I did something totally different than binary lifting https://cses.fi/paste/7ad0015ccbfbb625eaafe3/
I firstly, used segment tree to store the visible buildings list at each node (kind of merge sort tree), by nature of the constraint they will be sorted.
Now to query (L,R), First get the answer from the LEFT subtree, without any constraint, but for the right subtree, there is a constraint that only elements larger than the MAX of left subtree will be visible. So we propagate this threshold to the right subtree after computing the left subtree and then finally we merge both of the answers from left and right.
Code Link
I have also did a similar type of thing, i haven't created the merge sort trees I have used the pre-calculated answers from the left section to calculate the visible building in right subtree and finally store the height and visible building in the parent node.
This approach is space optimized.
For Minimal Grid Path in DP section. Here each (x,y) goes atmost once in queue and atmost twice in vector f. So its O(n^2). Let me know if I'm wrong in TC. Note: Its Accepted in CSES.
Thanks will be useful!!
https://cses.fi/paste/86e988fee98ea502edda28/
For the range interval queries, my solution which is O(q(logn)^2) giving TLE while submission.