Number of Squareful Arrays in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A of positive integers, we can say that array is squareful if for every pair of adjacent elements, their sum is a perfect square. We have to find the number of permutations of A that are squareful. Two permutations A1 and A2 will not be same if and only if there is some index i such that A1[i] not same as A2[i].

So, if the input is like [3,30,6], then the output will be 2, as we have two permutations like [3,6,30], [30,6,3].

To solve this, we will follow these steps −

  • Define a function isSqr(), this will take n,

    • x := square root of n

    • return true when (x * x) is same as n

  • Define a function solve(), this will take an array a, idx,

    • if idx is same as size of a, then −

      • (increase count by 1)

      • return

    • Define one set visited

    • for initialize i := idx, when i < size of a, update (increase i by 1), do −

      • if (idx is same as 0 or isSqr(a[idx - 1] + a[i])) and a[i] is not in visited then −

        • swap(a[idx], a[i])

        • solve(a, idx + 1)

        • swap(a[idx], a[i])

        • insert a[i] into visited

  • From the main method, do the following −

  • count := 0

  • solve(a, 0)

  • return count

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   int count;
   bool isSqr(lli n){
      lli x = sqrt(n);
      return x * x == n;
   }
   void solve(vector<int>& a, int idx){
      if (idx == a.size()) {
         count++;
         return;
      }
      set<int> visited;
      for (int i = idx; i < a.size(); i++) {
         if ((idx == 0 || isSqr(a[idx - 1] + a[i])) &&
         !visited.count(a[i])) {
            swap(a[idx], a[i]);
            solve(a, idx + 1);
            swap(a[idx], a[i]);
            visited.insert(a[i]);
         }
      }
   }
   int numSquarefulPerms(vector<int>& a){
      count = 0;
      solve(a, 0);
      return count;
   }
};
main(){
   Solution ob;
   vector<int> v = {3,30,6};
   cout << (ob.numSquarefulPerms(v));
}

Input

{3,30,6}

Output

2
raja
Updated on 04-Jun-2020 09:48:04

Advertisements