C++ program to check three items circularly likes next item or not


Suppose we have an array A with n elements. There are n planes on Earth and they are numbered from 1 to n. The plane with number i likes plane A[i]. A[i] != i. We have to check whether there are three planes p, q, and r where p likes q, q likes r and r likes p.

So, if the input is like A = [2, 4, 5, 1, 3], then the output will be True, because the triplet is [2, 4, 1].

Steps

To solve this, we will follow these steps −

n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   if A[A[A[i + 1]]] is same as i + 1, then:
      return true
return false

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();
   for (int i = 0; i < n; i++) {
      if (A[A[A[i + 1]]] == i + 1) {
         return true;
      }
   }
   return false;
}
int main() {
   vector<int> A = { 2, 4, 5, 1, 3 };
   cout << solve(A) << endl;
}

Input

{ 2, 4, 5, 1, 3 }

Output

1

Updated on: 03-Mar-2022

53 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements