Erase All But One
Erase All But One:
You are given a permutation of length . You can perform the following operation on :
- Choose any and such that and , and remove exactly one of them from the array. After removing, the remaining parts of the array are concatenated.
Find out if it is possible to apply the given operation any number of times such that only one element remains in the array.
Note: A permutation of length is an array where every element from to occurs exactly once.
Input Format
- The first line contains - the number of test cases. Then the test cases follow.
- The first line of each test case contains - the length of the permutation .
- The second line of each test case contains space-separated integers - elements of the permutation.
Output Format
For each test case, output YES if it is possible to reduce the array to a single element using the given operation. Otherwise, output NO.
You may print each character of the string in uppercase or lowercase (for example, the strings yEs, yes, Yes and YES will all be treated as identical).
Constraints
- form a permutation of length
- over all test cases is at most
Sample Input 1
3
4
3 1 2 4
3
2 3 1
6
5 2 3 6 1 4
Sample Output 1
YES
NO
YES
Explanation
- Test case : We can apply operations as follows (the bolded elements are the pair chosen for that operation):
- Test case : It can be shown that it is not possible to remove all elements except one element from the array.
- Test case : We can apply operations as follows:
SOLUTION:
#include <bits/stdc++.h>
using namespace std;
void testcase(){
int n;
cin >> n;
vector<int> v(n) , ind(n+1);
for(int i=0 ; i<n ; i++){
cin >> v[i];
ind[v[i]] = i;
}
int sm = ind[1];
vector<bool> vis(n+1 , 0);
vis[1] = 1;
stack<int> st;
for(int i=2 ; i<=n ; i++){
if(ind[i] > sm){
vis[i] = 1;
while(!st.empty()){
int top = st.top();
sm = min(sm , ind[top]);
vis[top] = 1;
st.pop();
}
}
else st.push(i);
}
for(int i=1 ; i<=n ; i++){
if(!vis[i]){
cout << "NO" << endl;
return;
}
}
cout << "YES" << endl;
}
int main() {
// your code goes here
int tt;
cin >> tt;
while(tt--){
testcase();
}
return 0;
}
Comments
Post a Comment