Alakazam has the unique ability to teleport itself during fights. He has realized that he can use this ability not just in Pokemon fights, but also during real-time manipulation of arrays. Abra, his non-evolution form has an interesting array of N integers, A1, A2, ..., AN-1, AN.
Since Alakazam wants to try his teleportation power on arrays too, he decides to formalize it: he can move from any position i to a position in an array of the world. Now, he is currently standing at a position he calls S. He wants you to figure out if he can reach position E.
Example:
Input: n = 5, a = [3,4,2,5,5], s = 1, e = 4
Output: Yes
Approach
C++
#include <bits/stdc++.h>using namespace std;bool thePsychicType(int n, int arr[], int s, int e){int a[n + 1];for (int i = 1; i <= n; i++)a[i] = arr[i - 1];set<int> st;st.insert(s);int flag = 0;while (s != e){s = a[s];if (st.find(s) != st.end()){flag = 1;break;}st.insert(s);}if (flag == 0)return true;elsereturn false;}int main(){int n = 5;int arr[] = {3, 4, 2, 5, 5};int s = 1, e = 4;if (thePsychicType(n, arr, s, e))cout << "Yes\n";elsecout << "No\n";return 0;}
No comments:
Post a Comment