题目描述
Chiaki has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 x n and numbers from 1 to n was written on each small 1 x 1 grid. Chiaki would like to fold the paper using the following operations:
- Fold the sheet of paper at position pi to the right. After this query the leftmost part of the paper with dimensions 1 x pi must be above the rightmost part of the paper with dimensions ).
- Fold the sheet of paper at position pi to the left. After this query the rightmost part of the paper with dimensions ) must be above the leftmost part of the paper with dimensions 1 x pi.
After performing the above operations several times, the sheet of paper has dimensions 1 x 1. If we write down the number on each grid from top to bottom, we will have a permutation of n.
Now given a permutation of n, Chiaki would like to know whether it is possible to obtain the permutation using the above operations.
输入描述:
There are multiple test cases. The first line of the input contains an integer T, indicating the number of test cases. For each test case:
The first line contains an integer n (1 ≤ n ≤ 106), indicating the length of the paper.
The second line contains n integers a1, a2, ..., an, which is a permutation of n, indicating the integers marked in the grids of the resulting sheet of paper from top to bottom.
It's guaranteed that the sum of n in all test cases will not exceed 106.
输出描述:
For each test case output one line. If it's possible to obtain the permutation, output ``Yes'' (without the quotes), otherwise output ``No'' (without the quotes).
示例1
输入
3
4
2 1 4 3
7
2 5 4 3 6 1 7
4
1 3 2 4
输出
Yes
Yes
No
思路:分为左右两边连线,连线不相交就成立。
#include<string.h>
#include<stdio.h>
#include<algorithm>
#include<stack>
#include<vector>
#define M 1000010
using namespace std;
struct node
{
int x,y;
node() {};
node(int a,int b)
{
x=min(a,b);
y=max(a,b);
}
};
vector<node>L,R;
int t,n,x;
int A[M],B[M];
int pan(vector<node>&v)
{
stack<int>q;
memset(B,0,4*(2+n));//改成menset(B,0,sizeof(B))会超时
int len=v.size();
for(int i=0; i<len; i++)
{
B[v[i].x]=i+1;
B[v[i].y]=-i-1;
}
for(int i=1; i<=n; i++)
{
if(B[i]>0)
q.push(B[i]);
else if(B[i]<0)
{
if(q.top()+B[i]==0)
q.pop();
else
return false;
}
}
return true;
}
int main()
{
scanf("%d",&t);
while(t--)
{
L.clear();
R.clear();
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%d",&x);
A[x]=i;
}
for(int i=1; i<n; i++)
{
node w(A[i],A[i+1]);
if(i&1) L.push_back(w);
else R.push_back(w);
}
if(pan(L)&&pan(R))
printf("Yes\n");
else
printf("No\n");
}
}