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?
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.
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.
6 1 2 5 3 4 6 01110
YES
6 1 2 5 3 4 6 01010
NO
In the first example you may swap a3 and a4, and then swap a4 and a5.
题意:
第一行一个数n
第二行 n 个 1~n 之间不同的数(存在arr数组里,从1开始)
第三行长度为n-1的字符串(只包含0和1),op[i]='1' 表示 arr[i]和arr[i+1]可以交换任意次
问能否将原数组变成递增数组
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int N = 200005;
int arr[N];
char op[N];
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&arr[i]);
scanf("%s",op+1);
for(int i=1;i<=n-1;i++){
if(op[i]=='1'){
int j=i;
while(j+1<=n-1&&op[j+1]==op[i]) j++;
sort(arr+i,arr+j+1+1);
i=j;
}
}
int flag=1;
for(int i=1;i<=n;i++)
if(arr[i]!=i){
flag=0;
break;
}
if(flag) printf("YES\n");
else printf("NO\n");
return 0;
}