C. Swap Adjacent Elements
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array.
For some indices i (1 ≤ i ≤ n - 1) it is possible to swap i-th element with (i + 1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap i-th element with (i + 1)-th (if the position is not forbidden).
Can you make this array sorted in ascending order performing some sequence of swapping operations?
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of elements in the array.
The second line contains n integers a1, a2, …, an (1 ≤ ai ≤ 200000) — the elements of the array. Each integer from 1 to n appears exactly once.
The third line contains a string of n - 1 characters, each character is either 0 or 1. If i-th character is 1, then you can swap i-th element with (i + 1)-th any number of times, otherwise it is forbidden to swap i-th element with (i + 1)-th.
Output
If it is possible to sort the array in ascending order using any sequence of swaps you are allowed to make, print YES. Otherwise, print NO.
Examples
inputCopy
6
1 2 5 3 4 6
01110
outputCopy
YES
inputCopy
6
1 2 5 3 4 6
01010
outputCopy
NO
Note
In the first example you may swap a3 and a4, and then swap a4 and a5.
题意:给你一个长度为n的数组,再给你一个字符串,只包含0和1,1代表这个数可以和它后面的那个数交换,0代表不能,问你通过多次交换,数组最后是否会按升序排列
思路:显然可以用另外一个数组保存输入的数组,然后将它排序,然后比较两个数组就可以了
详情看代码:
#include<bits/stdc++.h>
#define LL long long
#define Max 100005
const LL mod=1e9+7;
const LL LL_MAX=9223372036854775807;
using namespace std;
int a[2*Max],b[2*Max];
int n;
char s[2*Max];
set<int>p,q;//保存每次可交换的值
int main()
{
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%d",&a[i]),b[i]=a[i];
scanf("%s",s);
sort(b,b+n);
for(int i=0; i<n-1; i++)
{
if(s[i]=='1')//如果是1就将可以交换的数加入set,用set的原因是因为不仅可以去重还可以小到大排序
{
p.insert(a[i]),p.insert(a[i+1]);
q.insert(b[i]),q.insert(b[i+1]);
}
else//如果是0的话就比较是否可以通过交换让前面的数有序
{
if(a[i]!=b[i] && s[i-1]!='1'){//特例,这个数不可以交换,且它还不是有序的,直接输出NO
printf("NO\n");
return 0;
}
while(p.size() && q.size()){
if(*p.begin() != *q.begin()){
printf("NO\n");
return 0;
}
p.erase(p.begin());
q.erase(q.begin());
}
}
}
printf("YES\n");
return 0;
}