链接:http://codeforces.com/problemset/problem/1187/D
You are given an array a1,a2,…,an and an array b1,b2,…,bn
.
For one operation you can sort in non-decreasing order any subarray a[l…r]
of the array a
.
For example, if a=[4,2,2,1,3,1]
and you choose subbarray a[2…5], then the array turns into [4,1,2,2,3,1]
.
You are asked to determine whether it is possible to obtain the array b
by applying this operation any number of times (possibly zero) to the array a
.
Input
The first line contains one integer t
(1≤t≤3⋅105
) — the number of queries.
The first line of each query contains one integer n
(1≤n≤3⋅105
).
The second line of each query contains n
integers a1,a2,…,an (1≤ai≤n
).
The third line of each query contains n
integers b1,b2,…,bn (1≤bi≤n
).
It is guaranteed that ∑n≤3⋅105
over all queries in a test.
Output
For each query print YES (in any letter case) if it is possible to obtain an array b
and NO (in any letter case) otherwise.
Example
Input
4 7 1 7 1 4 4 5 6 1 1 4 4 5 7 6 5 1 1 3 3 5 1 1 3 3 5 2 1 1 1 2 3 1 2 3 3 2 1
Output
YES YES NO NO
Note
In first test case the can sort subarray a1…a5
, then a will turn into [1,1,4,4,7,5,6], and then sort subarray a5…a6.
题目大意:给一个数组a,一个数组b,每次可以选择数组a的一个区间并从小到大排序,问是否可以将数组a变成数组b。
思路:其实相当于每次可以选择相邻的两个数字,将其从小到大排序。因为任何区间进行排序后的结果,都可以由每次选两个相邻的数进行操作而得到。我们看一下第一个样例:
a:1 7 1 4 4 5 6
b:1 1 4 4 5 7 6
b[1]=a[1]=1,不用做操作;b[2]=1,所以要把a中的1即序列a的第三个数移动到第二个位置,这个操作需要满足条件:1是序列a的[1,3]内的最小值;此时若把做过操作的数置为INF,我们可:
a:INF 7 INF 4 4 5 6
b:1 1 4 4 5 7 6
b[3]=4,所以要把a中的4即序列a的第四个数移动到第三个位置,这个操作需要满足条件:4是序列a的[1,4]内的最小值;
以此类推……
我们可以发现,关键操作是对下标进行的,我们可以计算出一个wz数组,wz[i]表示序列b中下标为i的数是序列a中下标为wz[i]的那个数移动得到的,则对于上述样例我们有:
a: 1 7 1 4 4 5 6
b: 1 1 4 4 5 7 6
wz:1 3 4 5 6 2 7
然后遍历wz数组,查询序列a中[1,wz[i]]的最小值,看其是否等于b[i]即可,注意要把做过操作的数置为INF。
#include<iostream>
#include<cstdio>
#include<map>
#include<cmath>
#include<vector>
#define INF 0x3f3f3f3f
using namespace std;
int n,t;
vector<int> a[300005];
vector<int> b[300005];
int aa[300005];
int bb[300005];
int wz[300005];
int tree[300005];
inline int lowbit(int x)
{
return x&(-x);
}
void update(int x)
{
int lx,i;
while(x<=n)
{
tree[x]=aa[x];
lx=lowbit(x);
for(i=1;i<lx;i<<=1)
tree[x]=min(tree[x],tree[x-i]);
x+=lowbit(x);
}
}
int query(int r)//查询[1,r]
{
int ans=INF;
while(r)
{
ans=min(ans,tree[r]);
r-=lowbit(r);
}
return ans;
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&aa[i]);
for(int i=1;i<=n;i++)
scanf("%d",&bb[i]);
for(int i=1;i<=n;i++)
a[i].clear();
for(int i=1;i<=n;i++)
b[i].clear();
for(int i=1;i<=n;i++)
{
update(i);
a[aa[i]].push_back(i);
b[bb[i]].push_back(i);
}
int flag=0;
for(int i=1;i<=n;i++)
{
if(a[i].size()!=b[i].size())
{
flag=1;
break;
}
for(int j=0;j<a[i].size();j++)
wz[b[i][j]]=a[i][j]; //wz[i]表示序列bb中下标为i的数应该由aa中下标为wz[i]的数移动得到
}
if(flag)
printf("NO\n");
else
{
for(int i=1;i<=n;i++)
{
int r=wz[i];
int temp=query(r);
if(temp!=bb[i])
{
flag=1;
break;
}
aa[r]=INF;
update(r);
}
if(flag)
printf("NO\n");
else
printf("YES\n");
}
}
return 0;
}