MATDYS - Editorial

Problem Link

Practice
Contest

Author: Alexandru Valeanu
Tester: Hasan Jaddouh
Editorialist: Bhuvnesh Jain

Difficulty

EASY

Prerequisites

Observations

Problem

You are given a pack of 2^N cards and you shuffle it in N steps. At step k (0 ≤ k < N) you divide the deck into 2^k equal-sized decks. Each one of those decks is reordered by having all the cards that lie on even positions first, followed by all cards that lie on odd positions (the order is preserved in each one of the two subsequences). Then all decks are put back together (again, the order of decks is preserved).
Given an unordered deck of size 2^N, find the position of the card labelled K in the final, shuffled deck.

Quick Explanation

Check the binary representation of K and the final answer. Try to spot some observations.

Explanation

Subtask - 1

Since, N <= 10, we can simply simulate the whole process and find the exact order of the cards after all the N shuffles are done. The simply output the K^{th} index in the final array. The complexity of the above solution would be O(N*{2}^{N}) because there are total N steps of shuffling and each shuffles uses all the 2^N cards. This solution is thus too slow for the remaining subtasks.

Subtask - 2, 3 (Author’s Solution)

Let us try to find the binary representation of K and the final answer and try to spot some observations based on it. (Assume below that all binary representations are N bit long).

Let N = 3

Below is the table :

		K 				ANS
		000				000
		001				100
		010				010
		011				110
		100				001
		101				101
		110				011
		111				111

Do you spot the relationship between the two of them? Yes, the answer is simply the reverse of K in binary representation.

Thus, we can simply find the binary representation of K. Then try to construct the answer from the reverse of the binary representation found.

Subtask - 2, 3 (Editorialist’s Solution)

Since, K is of the order od 2^N, we would like to come up with an logarithmic approach in K or linear in N.

According to the way operations are performed, it is easy to see that once, 2 cards are separated into different decks, they can never appear in the same deck again. Thus we try to find how the cards of one deck are related to the other as same kind of operations (separating into decks and then reassembing based on even/odd combinations) is done of both of them.

Consider the operations one by one. Let K = 0, Here all the even numbers appear first in increasing order and then the odd numbers appear first. Thus, if we divide the array into 2 equal halves, we can see that numbers in right half are simply 1 (2^0), plus the numbers of the left side.

K = 0 -> 0 2 4 6 | 1 3 5 7

Now, let K = 1. The deck is divided into 4 halves and as per the first observation, cards in left deck of last operation cannot go to right deck of last operation. Thus, we would see how the leftmost 2 decks are related and the rightmost 2 decks are related. One can again see that for both halves, numbers of right deck are simply 2 (2^1), plus the numbers of the left side.

K = 1 -> 0 4 | 2 6 | 1 5 | 3 7

Thus, if we continue this procedure, we see that number of rigth side after i operations are simply 2^i plus the number of left side.

Thus, we now layout our algorithm, which is similar to binary search, as we would reduce our search space to half on each iteration and try to find the contribution of each step to the answer.

A similar problem using the above technique can be found out here

Pseudo Code

i = n-1 while(i >= 0): if (k > 2^i): //means lies of right side ans += 2^(n-1-i) k -= 2^i //move it to left side i -= 1 print(ans)

Some Silly Errors

Most of the participants, although found the correct logic but could not get full score. This is because of overflow in the answer. This is mostly the case in C++/Java users. If we use “long long”, the maximum limit is 63 bits on positive side and 63 bits on the negative side. To get full score, one had to use 64-bit representation i.e. “unsigned long long”. This should have been a good experience for some to learn about overflow cases in languages. Although python users had an advantage here as there is no overflow there.

Time Complexity

O(n) or O(\log{K})

Space Complexity

O(1)

Solution Links

Setter’s solution
Tester’s solution
Editorialist solution

7 Likes

Damn unsigned long long int!

Didnt strike me during contest and was suffering from overflow :frowning: . Switching to python was a savior though :slight_smile: (Stalking those python codes after long paid off :slight_smile: )

It feels bad when you skip the dinner for the contest but can only solve one problem ;_;
Grats to problem setter for a great “easy”(not for me though :p) level problem… It was really nerve stretching, at least for me!!

2 Likes

how can i improve my solution : https://www.codechef.com/viewsolution/15131329

@alexvaleanu I used unsigned long long int in C++14 but it still couldn’t store values as large as 2^64.

Had to resort to BigInteger in Java.

Any ideas why ? Please have a look solution link (I used the Binary Search approach)

I used unsigned long long int…but then also got wrong answer…can someone please help
https://www.codechef.com/viewsolution/15129654

I solved it using simple recursion in python

def f(n,k):
    if k==0:
        return 0
    if k%2==0:
        return f(n-1,k//2)
    return f(n-1,k//2)+2**(n-1)

t=int(input())
while t:
    t-=1
    [n,k]=list(map(int,input().split()))
    print(f(n,k))

Another O(N) approach:

The 2^n numbers can be divided into 2^{n-1} pairs mod 2^{n-1}. Observe that these modular residues pairs are arranged in the same order as the final ordering N = n-1.

For example - The final ordering for N=3 is \{0, 4, 2, 6, 1, 5, 3, 7\} which is equivalent to \{0,0,2,2,1,1,3,3\} (mod 4). This is the same as the final ordering for N = 2 i.e. \{0,2,1,3\}

With a recursive approach, we use the ordering for N=n-1 to obtain the ordering of the modulo pairs for N=n. Within the pair, the smaller number (which is strictly less than 2^{n-1}) comes first.

define f(n, k):
    if n==2:
        //Base case. Return the answer using the final ordering {0, 2, 1, 3}
    else:
        power = 2^(n-1) //use (1LL)<<(n-1)
        position = f(n-1, k % power) //recursion
        return 2*position + k/power //to handle ordering in the modulo pair
//n = 1 is handled separately

C++ code can be found here

1 Like

Iterate from the least significant bit to the most significant one,and use binary search to find position of number

1 Like

I am a newbie here,
As my answer my wrong, but I want to know, what was wrong with this:-
Initial array:-{0,1,2,3,4,5,6,7}
n=3
for any k, which is greater than or equal to n, the least size of the block will be 2.
Now after all the rearrangements the final array is {0,4,2,6,1,5,3,7}
Now my point is to swap the arr[1] with arr[1+pow(2,n-1)-1] and similarly with arr[3] until 1+pow(2,n-1)-1 < n.
Can anyone help??

Here is a simple O(logK) approach. It uses binary representation of K.

    #define ull unsigned long long

    int i=1;
    ull ans=0;
    while(k){
        if(k&1){
            ans+=(ull)pow(2,n-i);
        }
        k>>=1;
        i++;
    }
    cout<<ans;

The editorial does not explain why the binary representation of the answer is the reverse binary representation of K. What happens at every step k is that the rightmost N - k bits in the binary representation are cyclically shifted by one position to the right, so that the bit that was originally at position k from the right ends up at position k from the left.

Here is the implementation of this algorithm.

3 Likes

It was a great contest! One hardly learns much from easier contests, but tough contests give you an opportunity to learn a lot. Kudos to you problem setter!

Here, have a look at my solution. My observation was that once a number gets in a range whic was changed earlier, it never gets out of the range. And the numbers in the new range are always in a sorted order. Therefore, you can just check the index of number in that range, find the new index and reduce the range and repeat it n-1 times.

Solution.

What does the statement “numbers in right half are simply 1(2^0), plus the numbers of the left side.” mean exactly? Could you please provide examples? Thank you.

reading the editorial, and realizing i was so close ,seriously hurts .already solved k-char problem during the LOC, but when u fail to solve the similar problems just by some distance simple hurts , this teaches me that try till the last minute.

Edit: Fixed by Vijju123 Corrected code https://www.codechef.com/viewsolution/15138756

Original:

What’s wrong with my code/logic It fails on subtask 3 and runs on 1&2 (Lang Python 3) https://www.codechef.com/viewsolution/15128686

My logic:
Let N1=2^(N-1){length of subarrays}

If the K is even then it will go in the left part of the array and its position in the left array will be K/2
If the K is odd then it will go in the right part of array and its position in the right subarray will still be K/2 but it will have whole left subarray before it, hence add length of left subarray in it(store length of left subarray in variable pre)
Now in both the cases divide k by 2 (k/=2) and in odd case add N1 in the pre variable, divide N1=N1/2 because length of subarray will decrease by 2 in each run. Repeat this N times and final answer is pre+K

1 Like

Whats wrong with my code? Getting wrong answer on test 3 subtask 3.

https://www.codechef.com/viewsolution/15133990

Is n’t the Pseudo Code given wrong?

Subtask - 2, 3 (Author’s Solution)

Let us try to find the binary representation of K
and the final answer and try to spot some observations based on it. (Assume below that all binary representations are N

bit long).

Let N=3

Below is the table :

    K               ANS
    000             000
    001             100
    010             010
    011             110
    100             001
    101             101
    110             011
    111             111

Do you spot the relationship between the two of them? Yes, the answer is simply the reverse of K

in binary representation.

Thus, we can simply find the binary representation of K
. Then try to construct the answer from the reverse of the binary representation found.

Can someone provide me an implementation of this approach ?? Thanks in advance :slight_smile:

Is this the implementation of the above approach ??