makrav's blog

By makrav, 7 weeks ago, In English

Thank you for participating in the round!

2247A - Zero Sum

Hints
Solution
Code
Rate The Problem!

2247B - Yet Another Constructive

Hints
Solution
Code
Rate The Problem!

2247C - Inversion of a Subsequence

Hints
Solution
Code
Rate The Problem!

2247D1 - XOR Sorting (Easy Version)

Hints
Solution
Code
Rate The Problem!

2247D2 - XOR Sorting (Hard Version)

Hints
Solution
Code
Rate The Problem!

2247E - Build a Tree

Hints
Solution
Code
Rate The Problem!

2247F - Paths on a Grid

Hints
Solution
Code
Rate The Problem!
  • Vote: I like it
  • +115
  • Vote: I do not like it

»
7 weeks ago, hide # |
 
Vote: I like it +1 Vote: I do not like it

How do we solve E to have a chain based solution?I tried this in the contest but i couldn't find a solution.

  • »
    »
    7 weeks ago, hide # ^ |
    Rev. 2  
    Vote: I like it 0 Vote: I do not like it

    It's a similar sort of solution IMO, at least the way I did it. The answer can take the form of a central chain with some number of additional leaves hanging off, centered at 1. You can show that the maximum possible answer is generated from a chain that starts at 1 and alternately adds on the left and right sides. Note that this puts the evens one one side and the odds on the other, so each path always includes the center. You can take the step of moving a leaf toward the center incrementally, which decreases the sum by two, until the minimal possible answer of a star. Binary search to find an initial structure above but close to the desired k, whose sum is easy to calculate (there are multiple families that can be chosen here)

    • »
      »
      »
      6 weeks ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it

      Hi, "You can show that the maximum possible answer is generated from a chain that starts at 1 and alternately adds on the left and right sides" How did you show that this indeed is the max possible answer over all possible trees? I have a proof for but its quite complicated, do you have a simple one?

      • »
        »
        »
        »
        6 weeks ago, hide # ^ |
        Rev. 4  
        Vote: I like it 0 Vote: I do not like it

        Consider a maximal-distance tree, and consider some maximal path on that tree. If the path has a spur, say it has $$$x$$$ times the neighbor-cycle entering/exiting the spur goes left and $$$y$$$ times it goes right (with some number possibly going across). Then if $$$x\ge y$$$ reattach the spur on the right end otherwise reattach it on the left end; this will increase or maintain the total distance. This decreases the number of leaves by one; repeat until no spurs remain; this shows some chain is maximal. To see that my labeling scheme is optimal, consider that each edge on the chain is crossed at most $$$2*\text{min}(\text{left_size},\text{right_size})$$$ times, which is reached by my labeling.

  • »
    »
    7 weeks ago, hide # ^ |
    Rev. 2  
    Vote: I like it +14 Vote: I do not like it

    A chain-shaped tree of the form $$$1, 2, ..., n$$$ has sum $$$2(n - 1)$$$. This is the minimal sum which can be achieved; any additional sum requires rearranging the nodes. Let the remaining sum be $$$r = k - 2(n - 1)$$$. For starters, if $$$r \lt 0$$$, no valid arrangement exists.

    Try reversing two adjacent nodes in this chain. You'll notice that adjacent swaps involving the end elements ($$$1$$$ and $$$2$$$, or $$$n - 1$$$ and $$$n$$$) don't change the sum, whereas any other adjacent swap adds 2 to the sum. This is because any adjacent swap adds 2 to the number of times the edge between the nodes is crossed. In fact, the sum of distances for any tree is always even, as every edge must be crossed an even number of times. So if $$$r$$$ is odd, no valid arrangement exists either.

    If you try reversing longer contiguous subsequences of nodes, you'll notice that the amount added to the sum is equal to $$$2$$$ times the number of edges involved ($$$2(m - 1)$$$ for a contiguous subsequence of $$$m$$$ nodes). $$$m$$$ can be at most $$$n - 2$$$, because, as previously mentioned, reversing the end elements doesn't help us.

    But what if reversing every element between $$$1$$$ and $$$n$$$ isn't enough to reach $$$k$$$? The key insight here is that this is now a recursive problem. We simply repeat the same strategy on the reversed contiguous subsequence from $$$2$$$ to $$$n - 1$$$. Thus, we have turned this graph problem into a recursive array problem.

    Implementing said strategy results in an $$$\mathcal O(N)$$$ solution. For those looking for a (slightly messy) reference code, see my submission.

  • »
    »
    7 weeks ago, hide # ^ |
     
    Vote: I like it +1 Vote: I do not like it

    For anyone looking for a more detailed breakdown of Problem E, I wrote a separate tutorial focusing on the math intuition and the step-by-step visual construction of the chain-based solution (splitting evens and odds).

    You can read it here: Detailed Explanation

  • »
    »
    7 weeks ago, hide # ^ |
    Rev. 6  
    Vote: I like it 0 Vote: I do not like it

    I have a solution that is quite different, but it is a chain.

    So we start with the maximum total dist, by putting all odd numbers in order in front of even numbers, like 1 3 5 7 2 4 6 8 for n = 8. We try to move even numbers in front, one by one to reduce total dist, but not beyond the odd number that is smaller than it, as that will increase total dist. For simplicity(and to follow my code logic, I will be dividing dist and contribution by 2)

    For even n, swapping a even number 2a to one position to the front in the chain result in -2, -2, -2, ... -1 contribution, giving to total of 2 * (n/2-a)-1.

    For odd n, however, the contribution will be -1, -2, -2, -2, ... -1, giving a total of 2 * ((n+1)/2-a)-2. (swapping an even number with the last odd number will only give -1 here). Then we can use buckets to store where even numbers ended up at in the end, or to be more specific, which odd number is it after.

    Some more implementation details are in my code. My explanation is not that good so hopefully my code helps. (Somehow my code seem clearer than my explanation)

    383352745

  • »
    »
    7 weeks ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    Just find the pattern I think. For a chain from 1 to n, we can find moving any single node except 1 and n changes the contribution by 2. So we can move 2 to the end of the chain and then move 4 in order to not affect the change caused by moving 2. And we can move other even nums in the same way. In this way we can increase by 2 each time and construct it very easily.

  • »
    »
    7 weeks ago, hide # ^ |
    Rev. 2  
    Vote: I like it 0 Vote: I do not like it

    for E

    make edge case for n=2

    upperbound is n^2//2 lowerbound is 2n-2 k should be even if not satisfied return -1

    make edge 1 2 and 1 3 now we need to place n-3 more edges it can be seen that the min answer can be made by connecting all nodes to 1

    now how do we increase the answer? let x be 2*n-2 we increase answer from minimum

    make a left branch starting from 2 and a right branch starting from 3 for each i=4 to n if x+2*depth(left branch)<=k then append i to left/right branch according to parity of i-th node else we append i-th branch to depth of p where x+2*p==k

    once this condition satisfies append rest of the nodes to 1

    code: https://codeforces.me/contest/2247/submission/383475803

  • »
    »
    6 weeks ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    For a given edge, if $$$i$$$ is on the left side of that edge and $$$i+1$$$ is on the right side, then that edge’s contribution to the result increases by $$$2$$$.

    The minimum result is easy to construct: $$$1$$$~$$$2$$$~$$$3$$$~...~$$$n-1$$$~$$$n$$$

    Next, we will consider swapping adjacent numbers along this chain.

    First, move $$$n-1$$$ to the very front (note that the edge $$$1$$$–$$$2$$$ cannot further increase the result, so we will not swap $$$n$$$ and $$$n-1$$$); each swap increases the result by $$$2$$$.

    After the swap, the order of the chain becomes: $$$1$$$–$$$n-1$$$–$$$2$$$–$$$3$$$–...–$$$n-2$$$–$$$n$$$

    Note that the edge $$$1~2$$$ cannot further increase the result, so we do not move $$$n-1$$$ to the far left.

    Similarly, we move $$$n-3$$$ to the right of $$$n-1$$$, move $$$n-5$$$ to the right of $$$n-3$$$, and so on until the result can no longer be increased.

    This process is easy to implement; for details, see https://codeforces.me/contest/2247/submission/384141836.

»
7 weeks ago, hide # |
 
Vote: I like it +51 Vote: I do not like it

Was there any actual reason in D2 the constraints for n and q could go to 1000000? From what it looks like using n,q <= 200000 or 300000 or 500000 would have still ensured only the intended solutions really pass, and all 1000000 did was make the implementation in Python far more gimmicky and inconsistent than it needed to be. Also if there was some sort of weird O(n + q log n log n) type of solution you were trying to prevent with this constraint then I vehemently disagree with this choice as if someone really wanted they could ridiculously optimize their solution to make such a runtime work

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

such a fast Thanks

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

There is an issue in rate the problem

»
7 weeks ago, hide # |
 
Vote: I like it +1 Vote: I do not like it

is C solvable if we have to choose a subsegment instead of a subsequence? Because i misread subsequence as subsegment and couldnt solve it till i realized my mistake

»
7 weeks ago, hide # |
 
Vote: I like it +90 Vote: I do not like it

There is a nice hashing solution to F.

For a cell $$$c$$$, we denote $$$P(c)$$$ to be the set of paths that goes from $$$(1,1)$$$ to $$$(n,m)$$$ via $$$c$$$. Then, a set of cells $$$S$$$ is good if and only if for all $$$s \in S$$$, the sets $$$P(s)$$$ are the same.

We want to find a good way to hash the set of paths. To do so, we first assign a random weight to each edge (a downward / rightward move). We then let the hash value of a path from $$$(1,1)$$$ to $$$(n,m)$$$ to be the product of the weights that it passes through. Finally, for any cell $$$s$$$, we define the hash value of $$$P(s)$$$ to be the sum of the hash values of the paths passing through it.

This is convenient for us because the hash value $$$P(s)$$$ can be calculated easily with two DPs: we let $$$dp1[i][j]$$$ be the sum of hash value of all paths going from $$$(1,1)$$$ to $$$(i,j)$$$ only, and similarly $$$dp2[i][j]$$$ be the sum of hash value of all paths from $$$(n,m)$$$ to $$$(i,j)$$$. Then, $$$P((i,j))$$$ is just $$$dp1[i][j] \times dp2[i][j]$$$.

Our output is then obviously $$$\sum_{P(i,j)} 2^{\text{number of occurrences of }P(i,j)}-1$$$.

Submission: 383355741

  • »
    »
    7 weeks ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    im surprised this wasn't the intended solution given how clean it is

  • »
    »
    7 weeks ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    I'm sure the odds are extraordinarily low, but any idea what the odds of a hash collision are here?

    • »
      »
      »
      7 weeks ago, hide # ^ |
       
      Vote: I like it 0 Vote: I do not like it

      You can further find the dominance relationships corresponding to the path set, thus achieving deterministic $$$\mathcal{O}(nm)$$$, just like my approach below.

    • »
      »
      »
      6 weeks ago, hide # ^ |
      Rev. 3  
      Vote: I like it +8 Vote: I do not like it

      You can interpret the hash as a multivariate polynomial in $$$R[x_1,x_2,\dots, x_e]$$$ where the $$$x_i$$$ each correspond to an edge. The degree of the multivariate polynomial $$$P(s)$$$ is at most $$$n+m-2$$$, because down-right paths are of length at most $$$n+m-2$$$.

      By using this Schwartz Zippel Lemma you can prove that if you now substitute the $$$x_i$$$ with random values, and calculate the result mod a prime $$$p$$$, the chance that two non-identical path collections evaluate to identical is $$$\leq \frac{n+m-2}{p}$$$. To prove that the probability of a collision between any pair is small enough, we need to repeat this twice with some other independently random weights substituted, to get for example $$$\leq \left(\frac{n+m-2}{p}\right)^3$$$ probability of a single collision. The probability of any collision appearing for a distinct pair is then $$$ \leq 1- (1-(\frac{n+m-2}{p})^3 )^{{nm}\choose{2}}$$$. If you calculate this with some reasonable values for $$$n,m,p$$$ you'll notice that you need quite a number of hashes to get a provably correct algorithm (I am not sure if $$$3$$$ hashes is enough). In practice the collision probability for two $$$P(s)$$$ seems closer to $$$\frac{1}{p}$$$ and $$$3$$$ hashes does pass all the tests.

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

The one time I recognize a question used segment tree, I wasn't able to do it :(

»
7 weeks ago, hide # |
Rev. 2  
Vote: I like it +5 Vote: I do not like it

For problem F, we can indeed directly construct the graph and use the dominator tree to achieve a time complexity of $$$\mathcal{O}(nm \log (nm))$$$. However, due to the D/R operation on the plane, we can actually inductively derive the tightest constraint of the dominance relationship from the original graph, thus achieving a strict $$$\mathcal{O}(nm)$$$ time complexity with more concise logic.

In short, considering backwards, let $$$P(x,y)$$$ represent the set of all valid start-end paths passing through position $$$(x,y)$$$. Then, if $$$S$$$ is valid, it is true if and only if all positions $$$(x,y) \in S$$$ have the same $$$P(x,y)$$$. Therefore, we only need to find these equivalence classes. For a position $$$(x,y)$$$ that lies on at least one complete valid path, relative to the D/R operation, we can define $$$U_{x,y}$$$ and $$$L_{x,y}$$$ as the complete paths passing through the top and leftmost edges of $$$(x,y)$$$, respectively. Then, all paths passing through $$$(x,y)$$$ must be sandwiched between these two paths. Therefore, $$$P(x_1,y_1) = P(x_2,y_2)$$$ is actually equivalent to $$$U_{x_1,y_1} = U_{x_2,y_2}$$$ and $$$L_{x_1,y_1}=L_{x_2,y_2}$$$. We can dynamically transform these two paths into local variables based on how they were generated. For example, when entering a cell on the topmost path, it prioritizes entering from the top; otherwise, it enters from the left. When leaving, it prioritizes going right; otherwise, it goes down. From a topological sorting perspective, we can directly calculate $$$(U,L)$$$ for each position in order. Taking the generation of $$$U_{x,y}$$$ as an example, if the update $$$(i,j) \to (x,y)$$$ is along the priority direction, then $$$U_{i,j}=U_{x,y}$$$; otherwise, $$$U_{x,y}$$$ will have its own larger new id. Then we can directly use this pair as the basis for dividing equivalence classes.

For all positions not traversed by a complete path, they are grouped into a separate equivalence class. For an equivalence class $$$C$$$ of size $$$|C|$$$, the corresponding contribution is $$$2^{|C|} - 1$$$.

Thus, a solution with a deterministic $$$\mathcal{O}(nm)$$$ time and space complexity can be obtained directly using two rounds of counting sort/bucket sort.

my submission

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

383372267 My solution to D1 is quite simpler compared to the editorial ig. But i couldn't prove it properly it definitely works for distinct elements but i was confused about equal ones.

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

What if the array in Problem Aalso had 0 with 1 and -1 and everything else remain the same is it solvable then? if so how ? I could not think of anything

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

E IS AMAZING

»
7 weeks ago, hide # |
 
Vote: I like it +14 Vote: I do not like it

My contest discussion stream here for ABCD1D2

»
7 weeks ago, hide # |
 
Vote: I like it +3 Vote: I do not like it

I reached Expert in our final Binary Contest!!!

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

This contest went very bad for me. I read the question C but while thinking completely misremembered it as consecutive elements, which is much harder problem. It was such an easy problem to solve. So angry at myself.

»
7 weeks ago, hide # |
Rev. 2  
Vote: I like it 0 Vote: I do not like it

Another implementation for D1 : link

  • »
    »
    7 weeks ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    does this actually work? doesn't look correct to me. if you use stable sort then it can work. that is what i did. also you don't give compare function to sort. how can it know how to sort an array<ll,2>

»
7 weeks ago, hide # |
Rev. 3  
Vote: I like it 0 Vote: I do not like it

I wanted to share some intuition for D:

For a fixed $$$k$$$, define $$$p$$$ as the maximal power of $$$2$$$ less than or equal to $$$k$$$.

Beginning at index 0, we can swap with indices in the range $$$[0, p]$$$ as $$$0 \oplus x = x$$$ and the entire range $$$[0, p] \leq k$$$.

Beginning at index $$$p$$$, we can swap with indices in the range $$$[p, 2p - 1]$$$ as $$$p \oplus x = x - p$$$ when $$$x \in [p, 2p - 1]$$$, thus $$$p \oplus x \in [0, p - 1]$$$.

Note that $$$p \oplus 2p = 3p$$$ which would exceed our threshold of $$$k$$$, so we must stop at $$$2p - 1$$$.

Notice the overlap between the regions $$$[0, p]$$$ and $$$[p, 2p - 1]$$$. This gives us the ability to swap across regions, and sort the entire range $$$[0, 2p - 1]$$$.

More generally, for every aligned block $$$[2tp, 2(t+1)p - 1]$$$, the same argument applies because all indices share the same higher bits, so their XOR depends only on their positions within the block. No swap can cross between two such blocks, since indices in different blocks differ in a bit worth at least $$$2p \gt k$$$.

This explanation highlights why the answer should always be a power of $$$2$$$ (or $$$0$$$). The intervals we can sort are solely dependent on $$$p$$$, and $$$p$$$ only changes when $$$k$$$ reaches a power of 2. Thus choosing something like $$$k = 11$$$ is pointless when $$$k = 8$$$ gives you the exact same flexibility to swap.

D1: 383402115

D2: 383410424

  • »
    »
    7 weeks ago, hide # ^ |
    Rev. 2  
    Vote: I like it 0 Vote: I do not like it

    Thank you I was able to see the pattern but was not able to understand why this was working. One small correction, in the third line the set should be [0, p-1] instead of [0, p]

    edit: sorry my bad I'm dumb didn't read the explaination carefully

    • »
      »
      »
      7 weeks ago, hide # ^ |
      Rev. 2  
      Vote: I like it 0 Vote: I do not like it

      That is not a mistake. Consider when $$$k = p = 4$$$, then $$$0 \oplus p = 4$$$ and $$$ 4 \leq k$$$. If your change were correct, there would be no overlap between $$$[0, p - 1]$$$ and $$$[p, 2p - 1]$$$.

      • »
        »
        »
        »
        7 weeks ago, hide # ^ |
         
        Vote: I like it 0 Vote: I do not like it

        I think I also saw an alternate solution in which the answer was the highest power of 2 smaller than or equal to i^sorted(i) where i is the original index and sorted(i) is the index of the a[i] in sorted array. I wonder why this solution works...

        • »
          »
          »
          »
          »
          7 weeks ago, hide # ^ |
           
          Vote: I like it +3 Vote: I do not like it

          That is a nice simplification.

          As for why it works:

          Consider some $$$i$$$ and $$$j = sorted(i)$$$.

          For a fixed power of two $$$p$$$, we need both $$$i$$$ and $$$j$$$ to fall in the same $$$[2tp, 2(t + 1)p - 1]$$$ bucket. Since elements can never leave their connected component, this is precisely the condition required for the element at index $$$i$$$ to reach its destination.

          This condition is equivalent to the highest power of $$$2$$$ in $$$i \oplus j$$$ being at most $$$p$$$.

          Why? Consider the highest bit of $$$i \oplus j$$$, refer to this as bit $$$b$$$ (i.e. the $$$b$$$'th bit from the right, $$$0$$$-indexed). This is the highest bit where $$$i$$$ and $$$j$$$ differ. It follows that $$$i$$$ and $$$j$$$ are separated when considering groups of size $$$2^b$$$, but connected when considering groups of size $$$2^{b+1}$$$ (since $$$2^b$$$ is the largest group size that keeps them separated).

          Therefore, the minimum power of $$$2$$$ required for the element at index $$$i$$$ to reach its sorted position is exactly the highest power of $$$2$$$ contained in $$$i \oplus j$$$. Since every element must be able to reach its destination, the answer is the maximum of this quantity over all pairs $$$(i, sorted(i))$$$.

        • »
          »
          »
          »
          »
          7 weeks ago, hide # ^ |
           
          Vote: I like it 0 Vote: I do not like it

          I will add to the intuition of why in the first place pick p, which is highest power of 2 less than or equal to k

          think in terms of msb's, suppose you have some element which needs to be moved out of its msb position to some lower msb position(to be sorted), then analyze this situation and see what must be the lower bound of k, you will find out the power of 2.

»
7 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

How do you all develop the thinking? When I was solving question three, I could think that we need sum for mismatches in A. The only answers can be -1,0,1,2. 2 when sum is even cause we can only flip when sum is odd, hence with odd + odd which is even, the max flips we would need is 2. Also that if there is no 1, we can't flip in a so -1 if not same. But how did you think of all ones in B? did it just click or you all tried several cases here and there? And the questions after those, Haha~! I couldn't even understand them.

»
6 weeks ago, hide # |
Rev. 2  
Vote: I like it 0 Vote: I do not like it

**An O(N) purely constructive idea for E without LCA and Centroid **

Let's say n = 7.

Minimum sum of distances with a line graph (G1): 1-2-3-4-5-6-7 -> Sum: 12. Formula: 2*n — 2. Maximum sum of distances with a line graph (G2, one possibility): 1-3-5-7-6-4-2 -> Sum: 24.

How to get G2 (Maximum): To maximize dist(1, 2), keep '2' as far as possible from 1. Then for dist(2, 3), keep '3' as far as possible from '2'. From this intuition, you can build G2 to achieve the absolute maximum value.

How to build an intermediate graph for a required k: k must be in between this minimum and maximum value, and it can only increase by increments of +2.

Let's imagine the tree is rooted at '4'. If you swap 2 one position to the right in G1, the sum of the distance values for the new graph will increase by exactly 2 from the minimum value. For every right-side swap, the total distance increments by 2 (except for the final boundary position). Note that the distance sum of 1-3-4-5-6-2-7 and 1-3-4-5-6-7-2 will be the same, but we prefer the swap that brings 7 ahead to maintain array boundaries.

Allowed right-shifts (swaps) for each even number follows the formula (n — i — 1):

For 2, allowed swaps: 4 (since 7 — 2 — 1 = 4) For 4, allowed swaps: 2 For 6, allowed swaps: 0

From fully exhausting these swaps, the maximum distance we can add is (4 + 2) * 2 = 12. Total reach = minimum + 12 = 12 + 12 = 24 (which perfectly matches our maximum).

Take remaining = k — minimum. If you iterate step-by-step for each individual swap, it will result in Time Limit Exceeded (TLE). Instead, do it in O(1) chunks: check if it is possible to exhaust all allowed swaps for 2. If so, decrease remaining and move on to check 4. If only a fraction of the swaps are needed to hit the target k, simply take (remaining / 2) to get the exact required index shift.

These calculated "swaps" denote the number of indices an even value is shifted rightward from its starting configuration in the minimum graph (G1). We place the shifted even values into their final calculated indices, and then fill the empty slots with the remaining unused odd and even numbers in natural order.

The — i Offset: The final position of 4 will need to be shifted one index left from the absolute end because 2 has already been placed at the end. The position of 6 will be shifted two indices left because both 2 and 4 were placed before it. That is exactly why the index placements in the code subtract the iteration counter i:

g[node_num + max_inc + 1 — i] = node_num; g[node_num + c — i] = node_num;

you can see my submission here : 383463345

»
6 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

Simpler implementation for D1:

Code
»
6 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

can anyone explain Question b pls i didn't get the editorial

»
6 weeks ago, hide # |
Rev. 3  
Vote: I like it 0 Vote: I do not like it

Another construction for E:

Take the form $$$1, n, n-1, n-2 \cdots 2$$$. Initialize $$$t = 0$$$

If $$$t \equiv 0 \operatorname{mod} 2$$$, take $$$(t+ 1)^{th}$$$ element and keep swapping with adjacent elements until there remain $$$t + 1$$$ elements in the suffix(not including the chosen element itself). Then at the end do $$$t$$$++.

If $$$t \equiv 1 \operatorname{mod} 2$$$, skip. $$$t$$$++.

Now the answer can be found by simple binary search.

For every swap, the answer increments by 2 and thus the total number of swaps and the actual possible answers match. While not a mathematical proof, it is mathematical evidence. Off to sleep now...

»
6 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

No way D1 and D2 core bitwise logic strike between timed contest!!! bruhh..

»
6 weeks ago, hide # |
Rev. 2  
Vote: I like it 0 Vote: I do not like it

I strongly recommend that make D2's time limit higher,like to make it to 3 seconds.

»
6 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

What about this solution for E

I guess my this solution is much easier to implement:

void luffy() {
    ll n,k;cin>>n>>k;
    if(!(k>=2*(n-1) && k<=(n*(n-1))/2 +n/2)){
        cout<<-1<<endl;
        return;
    }
    if((k-2*(n-1))%2){
        cout<<-1<<endl;
        return;
    }
    vector<ll>v(n+1,-1);
    // iota(all(v),1);


    ll dif=k-2*(n-1);
    vector<vector<ll>>g(n+1);
    for(ll i=2;i<=n;++i){
        g[1].push_back(i);;
    }
    if(n==2){
        cout<<1<<" "<<2<<endl;
        return;
    }
    vector<ll>odd,even;
    for(ll i=3;i<=n;i+=2){
        odd.push_back(i);
    }
    
    for(ll i=2;i<=n;i+=2){
        even.push_back(i);
    }
    ll op=dif/2;
    vector<ll>vis(n+1);
    vector<ll>parent(n+1);
    for(ll i=1;i<=n;++i)parent[i]=1;
    ll o=1,e=1;
    ll ol=(n+1)/2 -2;
    ll el=(n)/2 -1;
   
        ll kk=2;
        while(o<odd.size() && dif){
            if(dif-kk>=0){
                dif-=kk;
                kk+=2;
                parent[odd[o]]=odd[o-1];

                o++;
            }
            else{
                break;
            }
        }
        if(o!=odd.size() && dif){
            // kk-=2;
            kk=dif;
            ll lvl=dif/2;

            ll xx=odd[lvl-1];
            while(dif && o<odd.size()){
                if(dif-kk>=0){
                    dif-=kk;
                    parent[odd[o]]=xx;

                    o++;
                }
                else{
                    break;
                }
            }
        }

  kk=2;
        while(e<even.size() && dif){
            if(dif-kk>=0){
                dif-=kk;
                kk+=2;
                parent[even[e]]=even[e-1];

                e++;
            }
            else{
                break;
            }
        }
        if(e!=even.size() && dif){
            kk=dif;
            ll xx=even[dif/2-1];
            while(dif && e<even.size()){
                if(dif-kk>=0){
                    dif-=kk;
                    parent[even[e]]=xx;

                    e++;
                }
                else{
                    break;
                }
            }
        }
        for(ll i=2;i<=n;++i){
            cout<<i<<" "<<parent[i]<<endl;
        }



}
»
5 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

For D1, my method:

First, stably sort the array (by value, then by original index). For every element whose position changes, compute the XOR of its original index and its new index. The answer is the maximum highest power of two among these XOR values.

It's pretty simple to implement.

»
4 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

I wrote a slightly better time complexity code for problem E Build a Tree

If it wasn't for printing edges my code beats solution code in processing

I request anyone to check if my code gives correct output for entire input space

Approach : Find largest number where this condition hold true

(k >= (m* m) / 2 + 2 * (n — m))

construct largest k for whose m edges : as in b2 (function)method continue this process for k-m(m)/2 and soon until k>remaining_n(remaining_n)/2 logic is provided im below code to handle remaining_n

»
3 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

For D1, a lot of people (including me) seem to have come across the solution of creating a new array $$$b$$$ where $$$b_i = [a_i, i]$$$, sorting it, and taking the maximum value of $$$\operatorname{msb}(i, b_{i_2})$$$. Two things:

1: I haven't seen anyone write a proof for it. While I won't write a full proof, it can be proved with the following two observations:

  • The maximum MSB of swaps that don't move target elements into place will always be less than or equal to the maximum MSB of swaps that move target elements into place.

  • If multiple elements are equal, it is optimal to put the element with the maximum original index into the maximum target index.

2: Is this solution extendable into D2?

»
3 weeks ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

I feel so confused ,for C, if a=[1,0,1,0],b=[1,1,1,0],why the answer is 2, I can't find the way

»
3 weeks ago, hide # |
Rev. 2  
Vote: I like it 0 Vote: I do not like it

PvPro why the ans of the test case : a = 1 0 0 b = 1 1 1 is 2 and why not -1 ??

  • »
    »
    2 weeks ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    For a = [1,1,1] and b = [0,0,0]:

    Choose all three elements. Their sum is 3, which is odd, so the operation is allowed.

    Flip them: [1,1,1] → [0,0,0].

    So the answer is 1, not -1.