codeforces920 C. Swap Adjacent Elements【连通块 + 前缀和】

C. Swap Adjacent Elements

time limit per test1 second
memory limit per test256 megabytes

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

input

6
1 2 5 3 4 6
01110

output

YES

input

6
1 2 5 3 4 6
01010

output

NO

Note

In the first example you may swap a3 and a4, and then swap a4 and a5.

题意 :已知有不重复的n个数组成的排列,给你[1,n - 1]这些点的可交换性,问你可否把这个排列,变成严格递增的,其中可交换性指的是a[i] 可以和 a[i + 1]交换,用长度为n - 1 的字符串表示,‘0’代表当前位置不可交换,‘1’代表可交换

分析: 当前仅当 位置i和位置j可交换的充要条件为 s[i],s[i + 1]···,s[j - 1]都为1时,所以我们可以维护s数组的前缀和,做到 O(1) O ( 1 ) 查询

参考代码

#include

using namespace std;

const int maxn = 1e6 + 10;
int pre[maxn];
int a[maxn];

int main(){
    ios_base::sync_with_stdio(0);
    int n;cin>>n;
    for(int i = 1;i <= n;i++) {
        cin>>a[i];
    }
    string s;cin>>s;
    for(int i = 1;i <= s.size();i++) {
        pre[i] = pre[i - 1] + s[i - 1] - '0';
    }
    for(int i = 1;i <= n;i++) {
        if(a[i] != i) {
            int ma = max(a[i],i);
            int mi = min(a[i],i);

            if(pre[ma - 1] - pre[mi - 1] != ma - mi) {
                cout<<"NO"<return 0;
            }
        }
    }
    cout<<"YES"<return 0;
}
  • 如有错误或遗漏,请私聊下UP,thx

你可能感兴趣的:(前缀和)