C++ Program to check we can remove all stones by selecting boxes


Suppose we have an array A with N elements. Consider there are N boxes and they are arranged in a circle. The ith box contains A[i] stones. We have to check whether we can remove all stones from the boxes by repeatedly performing the operation: Select a box say ith box. For each j in range 1 to N, remove exactly j stones from the (i+j)th box. Here (N+k)th box is termed as kth box. This operation cannot be performed if a box does not contain sufficient number of stones.

So, if the input is like A = [4, 5, 1, 2, 3], then the output will be True, because we can remove all stones by starting from second box.

To solve this, we will follow these steps −

n := size of A
Define an array a of size (n + 1)
Define an array b of size (n + 1)
sum := 0, p := n * (n + 1)
for initialize i := 1, when i <= n, update (increase i by 1), do:
   a[i] := A[i - 1]
   sum := sum + a[i]
if sum mod p is not equal to 0, then:
   return false
k := sum / p
for initialize i := 1, when i <= n, update (increase i by 1), do:
   b[i] := a[i] - a[(i mod n) + 1]
sum := 0
for initialize i := 1, when i <= n, update (increase i by 1), do:
   a[i] := b[i]
   sum := sum + a[i]
if sum is not equal to 0, then:
   return false
for initialize i := 1, when i <= n, update (increase i by 1), do:
   if (a[i] + k) mod n is not equal to 0 or a[i] + k < 0, then:
      return false
return true

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
bool solve(vector<int> A) {
   int n = A.size();
   vector<int> a(n + 1);
   vector<int> b(n + 1);
   int sum = 0, p = n * (n + 1) / 2;
   for (int i = 1; i <= n; i++) {
      a[i] = A[i - 1];
      sum += a[i];
   }
   if (sum % p != 0) {
      return false;
   }
   int k = sum / p;
   for (int i = 1; i <= n; i++) {
      b[i] = a[i] - a[i % n + 1];
   }
   sum = 0;
   for (int i = 1; i <= n; i++) {
      a[i] = b[i];
      sum += a[i];
   }
   if (sum != 0) {
      return false;
   }
   for (int i = 1; i <= n; i++) {
      if ((a[i] + k) % n != 0 || a[i] + k < 0) {
         return false;
      }
   }
   return true;
}
int main(){
   vector<int> A = { 4, 5, 1, 2, 3 };
   cout << solve(A) << endl;
}

Input

{ 4, 5, 1, 2, 3 }

Output

1

Updated on: 25-Feb-2022

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements