Find a permutation of 2N numbers such that the result of given expression is exactly 2K in C++


Suppose we have two integers N and K. We have to find first permutation of 2N number of natural numbers, such that the following equation is satisfied.

$$\displaystyle\sum\limits_{i=1}^N\lvert A_{2i-1}-A_{2i}\rvert+\lvert \displaystyle\sum\limits_{i=1}^N A_{2i-1}-A_{2i} \rvert=2K$$

The value of K should be less than or equal to N. For example, if N = 4 and K = 1, then output will be 2 1 3 4. The result of the given expression will be (|2 – 1| + |3 – 4|) – (|2 – 1 + 3 – 4|) = 2.

The idea is simple, consider we have a sorted sequence like 1, 2, 3, 4, 5, 6, …. If we swap any two indices 2i – 1 and 2i, the result will increase by exactly 2. We need to make K such swaps.

Example

 Live Demo

#include<iostream>
using namespace std;
void showPermutations(int n, int k) {
   for (int i = 1; i <= n; i++) {
      int a = 2 * i - 1;
      int b = 2 * i;
      if (i <= k)
         cout << b << " " << a << " ";
      else
         cout << a << " " << b << " ";
   }
}
int main() {
   int n = 4, k = 2;
   showPermutations(n, k);
}

Output

2 1 4 3 5 6 7 8

Updated on: 18-Dec-2019

39 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements