A train moves from A through a station to B.
Initially, the coaches of the train is numbered by 1,2,...n.
You want to know whether you can rearrange the coaches in the order: a1,a2,...an .
Each coach can be disconnected from the train and
enter the station from A and leave the station to B ,
or move directly from A to B without entering the station.
A coach can only leave the station if the coaches arriving before it have left the station.
Given a1,a2,...an , please output
YES, if it is possible to rearrange the coaches.
NO, if it is impossible.
Input Format
The first line is an integer denoting the number of queries.
For each query, there are 2 lines:
The first line is an integer , i.e. number of coaches.
The second line is an integer sequence
Sample Input 0
3
5
3 4 1 2 5
5
1 2 3 4 5
5
5 4 3 2 1
Sample Output 0
YES
YES
NO
My code shows success in most test cases, but got one wrong answer in a test case. Don't know how to modify it, or is there a better way to write the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
#include <iostream>
#include <queue>
#include <vector>
#include <stdio.h>
using namespace std;
int main(void)
{
int T;
cin >>T;
while (T--)
{
int n;
cin >> n;
vector<int> target(n);
target.clear();
for (int i = 0; i < n; i++)
{
cin >> target[i];
}
int num=1,a=0,ans=1;
queue<int> s;
while(a<n)
{
if(target[a]==num)
{ a++; num++;}
else if(!s.empty() && s.front()==target[a])
{s.pop();a++;}
else if(num<=n)
{
s.push(target[a++]);
num++;
}
else
{
ans=0;
break;
}
}
if (ans)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
return 0;
}
|