传送门:点我
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
6
1 2 5 3 4 6
01110
YES
6
1 2 5 3 4 6
01010
NO
Note
In the first example you may swap a3 and a4, and then swap a4 and a5.
题意:
给定1~n的序列(所有数刚好出现一次),然后再给01串,01串中如果是1,则可以交换当前位置和下一个位置的数字。问是否能还原为递增数组。
思路:
如果当前数的01串对应是0,且前一个位置01串也是0,且当前数字与下标不对应,肯定输出NO,因为没法交换
然后对可以交换的部分记录下最大最小值,然后记录下起始位置和终点位置,比较一下就行了。
比如说第一组数据
6
1 2 5 3 4 6
01110
01串第一个是0,对应上去是1,下标也是1,则可以。
然后从2~4都是可以交换的范围(即连续的1,然后后面第一个0)
保留下最大值是4,最小值是2,起始位置2,末尾位置4。一一对应了,就输出YES。
代码:
#include<stdio.h> #include<string.h> #include<string> #include<math.h> #include<vector> #include<queue> #include<stack> #include<set> #include<iostream> #include<algorithm> using namespace std; typedef long long LL; int read(){ char c; bool op = 0; while((c = getchar()) < '0' || c > '9') if(c == '-') op = 1; int res = c - '0'; while((c = getchar()) >= '0' && c <= '9') res = res * 10 + c - '0'; return op ? -res : res; } const int maxn = 1e6+7; int a[maxn]; int main() { int n; scanf("%d",&n); for(int i = 1 ; i <= n ; i++) scanf("%d",&a[i]); int Max = 0,Min = n+1; int flag = 0,ardMin; getchar(); for(int i = 1 ; i <= n - 1 ; i++){ char c; scanf("%c",&c); if(flag == 0 && c == '1'){ ardMin = i; } if(c == '0' && flag == 1){ Max = max(Max,a[i]); Min = min(Min,a[i]); if(ardMin!= Min || Max != i){ return puts("NO"),0; } Max = 0;Min = n+1; flag = 0; } else if(c == '1'){ Max = max(Max,a[i]); Min = min(Min,a[i]); flag = 1; } else if(c == '0'&& a[i] != i){ return puts("NO"),0; } } return puts("YES"),0; } /* 6 1 3 2 4 6 5 01000 */