【CodeForces 1365B --- Trouble Sort】

【CodeForces 1365B --- Trouble Sort】

題目來源:點擊進入【CodeForces 1365B — Trouble Sort】

Description

Ashish has n elements arranged in a line.

These elements are represented by two integers ai — the value of the element and bi — 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 ai.

He can perform the following operation any number of times:

  • Select any two elements i and j such that bi≠bj 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 ai after performing any number of operations.

Input

The first line contains one integer t (1≤t≤100) — the number of test cases. The description of the test cases follows.

The first line of each test case contains one integer n (1≤n≤500) — the size of the arrays.

The second line contains n integers ai (1≤ai≤105) — the value of the i-th element.

The third line containts n integers bi (bi∈{0,1}) — the type of the i-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).

Sample Input

5
4
10 20 20 30
0 1 0 1
3
3 1 2
0 1 1
4
2 2 4 8
1 1 1 1
3
5 15 4
0 0 0
4
20 10 100 50
1 0 0 1

Sample Output

Yes
Yes
Yes
No
Yes

Note

For the first case: The elements are already in sorted order.

For the second case: Ashish may first swap elements at positions 1 and 2, then swap elements at positions 2 and 3.

For the third case: The elements are already in sorted order.

For the fourth case: No swap operations may be performed as there is no pair of elements i and j such that bi≠bj. The elements cannot be sorted.

For the fifth case: Ashish may swap elements at positions 3 and 4, then elements at positions 1 and 2.

解題思路:

本題只需要考慮兩種情況:

  • b[i]都相同,如果b[i]都相同,那麼我們只需要判斷a[i]是否已經排好。
  • b[i]存在不同元素,如果存在不同元素,那麼我們就可以通過不同的那個元素改變每個元素的位置,所以肯定yes.

AC代碼(C++):

#include <bits/stdc++.h>
using namespace std;
#define SIS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define endl '\n'
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const int MAXN =505;
pair<int,int> arr[MAXN];

int main(){
    int t,n;
    cin >> t;
    while(t--){
        cin >> n;
        bool flag=false,f1=false;
        for(int i=0;i<n;i++){
            cin >> arr[i].first;
            if(i && arr[i].first<arr[i-1].first) f1=true;
        }
        if(!f1) flag=true;
        for(int i=0;i<n;i++){
            cin >> arr[i].second;
            if(i && arr[i].second!=arr[i-1].second) flag=true;
        }
        if(flag) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章