- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements