- 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
C++ program to find permutation for which sum of adjacent elements sort is same as given array
Suppose we have an array A with n elements. A function F(p) is a sorted array of sums of adjacent elements in p. So F(p) = sort([p1 + p2, p2 + p3, ... pn-1 + pn]). We have a permutation represented in A. We have to find the different permutation of A where F(A) is same.
So, if the input is like A = [2, 1, 6, 5, 4, 3], then the output will be [1, 2, 5, 6, 3, 4], because F(A)=sort([2+1, 1+6, 6+5, 5+4, 4+3]) = sort([3, 7, 11, 9, 7]) = [3,7,7,9,11]. And sort([1+2, 2+5, 5+6, 6+3, 3+4]) = sort([3, 7, 11, 9, 7]) = [3, 7, 7, 9, 11]. (There can be other answers too)
Steps
To solve this, we will follow these steps −
n := size of A for initialize i := n - 1, when i >= 0, update (decrease i by 1), do: print A[i]
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; void solve(vector<int> A) { int n = A.size(); for (int i = n - 1; i >= 0; i--) cout << A[i] << ", "; } int main() { vector<int> A = { 2, 1, 6, 5, 4, 3 }; solve(A); }
Input
{ 2, 1, 6, 5, 4, 3 }
Output
3, 4, 5, 6, 1, 2,
Advertisements