练习cf1365B. Trouble Sort
题目如下
Ashish has 𝑛 elements arranged in a line.
These elements are represented by two integers 𝑎𝑖 — the value of the element and 𝑏𝑖 — the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of 𝑎𝑖.
He can perform the following operation any number of times:
Select any two elements 𝑖 and 𝑗 such that 𝑏𝑖≠𝑏𝑗 and swap them. That is, he can only swap two elements of different types in one move.
Tell him if he can sort the elements in non-decreasing values of 𝑎𝑖 after performing any number of operations.
Input
The first line contains one integer 𝑡 (1≤𝑡≤100) — the number of test cases. The description of the test cases follows.
The first line of each test case contains one integer 𝑛 (1≤𝑛≤500) — the size of the arrays.
The second line contains 𝑛 integers 𝑎𝑖 (1≤𝑎𝑖≤105) — the value of the 𝑖-th element.
The third line containts 𝑛 integers 𝑏𝑖 (𝑏𝑖∈{0,1}) — the type of the 𝑖-th element.
Output
For each test case, print "Yes" or "No" (without quotes) depending on whether it is possible to sort elements in non-decreasing order of their value.
You may print each letter in any case (upper or lower).
题目大意
现有数组,值存放在ai中,属性分为“0”,“1”两种,存放在bi中,现在需要把题目整理成递增的数组,但每次操作只能交换两个属性不同的元素,若可以输出“YES‘,否则”NO“
题目分析
只要b数组中存在不同属性的元素,就一定可以将数组a的有序化。
所以原则是只要判断数组b中是否出现了不同的元素即可。
完整代码
点击查看代码
#include <vector>
#include <algorithm>
using namespace std;
bool is_sorted(int a[], int n){
for(int i = 1; i < n; i++){
if(a[i] < a[i - 1]){
return false;
}
}
return true;
}
int main(){
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
int a[505];
vector<int> b;
for(int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
for(int i = 0; i < n; i++){
int bb;
scanf("%d",&bb);
b.push_back(bb);
}
if(is_sorted(a, n) || (find(b.begin(),b.end(), 0) != b.end()
&& find(b.begin(),b.end(), 1) != b.end())){
printf("Yes\n");
}else{
printf("No\n");
}
}
return 0;
}

浙公网安备 33010602011771号