Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Beautiful Arrangement in C++
Suppose we have N integers from 1 to N. We will define a beautiful arrangement as an array that is constructed by these N numbers completely if one of the following is true for the ith position (1 <= i <= N) in this array −
- The number at the ith position is can be divided by i.
- i is divisible by the number at the ith position.
So if the input is 2, then the result will be also 2, as the first beautiful arrangement is [1,2]. Here number at the 1st position (i=1) is 1, and 1 is divisible by i (i=1). Then number at the 2nd position (i=2) is 2, and 2 is divisible by i (i=2). The second beautiful arrangement is [2, 1]: Here number at the 1st position (i=1) is 2, and 2 is divisible by i (i=1). Then number at the 2nd position (i=2) is 1, and i (i=2) is divisible by 1.
To solve this, we will follow these steps −
- Define a recursive method solve(), that will take visited array, end and pos. The pos is initially 1.
- if pos = end + 1, then increase ans by 1 and return
- for i in range 1 to end
- if i is not visited and pos is divisible by 0 or i is divisible by 0, then
- mark i as visited
- solve(visited, end, pos + 1)
- mark i as unvisited
- if i is not visited and pos is divisible by 0 or i is divisible by 0, then
- from the main method, do the following −
- ans := 0, make an array called visited
- call solve(visited, N, 1)r
- return ans.
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int ans;
void solve(vector <bool>& visited, int end, int pos = 1){
if(pos == end + 1){
ans++;
return;
}
for(int i = 1; i <= end; i++){
if(!visited[i] && (pos % i == 0 || i % pos == 0)){
visited[i] = true;
solve(visited, end, pos + 1);
visited[i] = false;
}
}
}
int countArrangement(int N) {
ans = 0;
vector <bool> visited(N);
solve(visited, N);
return ans;
}
};
main(){
Solution ob;
cout << (ob.countArrangement(2));
}
Input
2
Output
2