Swap Adjacent Elements

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.

Example
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所以正常的顺序应该是第i个元素就是i所以如果第i个元素的值是i+k那么,肯定要把i+k从i通过对换移动到i+k位置,所以需要i到i+k-1位置都可以对换,只需要判断元素比下标值大的,或者元素比下标值小的,如果其中任何一方归位了,另一方也就归位了。一开始直接for循环判断,超时了,又注意到是区间记录,用了个树状数组。

代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cmath>

using namespace std;
int s[200001],n,d;
char str[2000001];
int digit(int t)
{
    return t&-t;
}
void update(int x,int y)
{
    while(x <= n)
    {
        s[x] += y;
        x += digit(x);
    }
}
int get(int x)
{
    int ans = 0;
    while(x > 0)
    {
        ans += s[x];
        x -= digit(x);
    }
    return ans;
}
int check()
{
    int d = 0;
    for(int i = 1;i < n;i ++)
    {
        d = get(i);
        if(d && str[i - 1] == '0')return 0;
    }
    return 1;
}
int main()
{
    scanf("%d",&n);
    for(int i = 1;i <= n;i ++)
    {
        scanf("%d",&d);
        if(d > i)
        {
            update(i,1);
            update(d,-1);
        }
    }
    scanf("%s",str);
    if(check())cout<<"YES";
    else cout<<"NO";
}
原文地址:https://www.cnblogs.com/8023spz/p/8433192.html