Codeforces Round #648 (Div. 2) B. Trouble Sort

一开始读错题了...想当然地认为只能相邻元素交换...(然后换了两种写法WA了4发,5分钟切A的优势荡然无存)

题目链接:https://codeforces.com/contest/1365/problem/B

题意

有 $n$ 个数,每个数的种类为 $0$ 或 $1$,不同种类的元素可以任意交换,问这些数能否排为非递减序。

题解

如果两个种类都有,一定可以排为有序,稍微证明一下:

  1. 将种类为 $0$ 的数都交换到最左边,种类为 $1$ 的数都交换到最右边
  2. 每个种类的数可以利用另一个种类的一个数作为中转进行内部排序
  3. 最后再对两个种类进行整体排序即可

如果只有一种判断是否已排序即可。

代码

#include <bits/stdc++.h>
using namespace std;

void solve() {
    int n; cin >> n;
    int a[n]; for (auto &i : a) cin >> i;
    int b[n]; for (auto &i : b) cin >> i;
    sort(b, b + n);
    bool ok = true;
    if (b[0] == b[n - 1])//只有一种
        ok = is_sorted(a, a + n);
    cout << (ok ? "Yes" : "No") << "
";
}

int main() {
    int t; cin >> t;
    while (t--) solve();
}
原文地址:https://www.cnblogs.com/Kanoon/p/13063309.html