cf - 920 c 求能否实现交换
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.
题目分析 : 一串数字,还有一串字符串,为 1 的时候当前的数字可以和它下一位去交换,然后这么想,对于一个不在当前位置的数字,如果它大于当前的位置,那么它如果想要被交换到相应的位置,那么字符串的当前位置和要交换到的位置的前一个字符就应该都是 1 ,那么前缀和去处理字符串就可以了,还有就是只需要考虑数大于当前位置的情况,大的满足,小的一定成立。
代码示例 :
const int eps = 2e5+5; const double pi = acos(-1.0); const int inf = 1<<29; #define Max(a,b) a>b?a:b #define Min(a,b) a>b?b:a #define ll long long int pre[eps]; char s[eps]; int arr[eps]; int main() { //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n; cin >> n; for(int i = 1; i <= n; i++){ scanf("%d", &pre[i]); } scanf("%s", s+1); for(int i = 1; i < n; i++){ if (s[i] == '1') arr[i] = 1; else arr[i] = 0; arr[i] += arr[i-1]; } //for(int i = 1; i < n; i++){ //printf("%d ", arr[i]); //} //printf("\n"); int sign = 0; for(int i = 1; i < n; i++){ if (pre[i] > i) { int f = arr[pre[i]-1] - arr[i-1]; if (f != pre[i]-i) {sign = 1; break;} } if (sign) break; } if (!sign) printf("YES\n"); else printf("NO\n"); return 0; }