CF220A Little Elephant and Problem 题解
Notice
由于第一次使用 Ubuntu 写代码,所以代码风格可能和之前的题解有所不同,请见谅qwq。
Content
有一个长度为 \(n\) 的序列 \(a_1,a_2,a_3,...,a_n\),求是否可以通过不多于一次的交换使得这个序列变成非降序序列。
数据范围:\(2\leqslant n\leqslant 10^5,a_i\leqslant 10^9\)。
Solution
我们可以开两个数组,一个就是我们当前的数组,另外一个做辅助用。首先我们将辅助数组一一对应赋值为输入的数组的值。然后对这个辅助数组非降序排序。我们知道,交换一次会有 \(2\) 个值与原来的不同,所以我们将输入的数组和排序后的数组比较看有多少个值不同,如果不同的数量 \(> 2\),那么就无法通过最多一次的交换使得这个序列变成非降序序列,否则可以。
Code
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
using namespace std;
int n, a[100007], a1[100007], scnt;
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
a1[i] = a[i];
}
sort(a1 + 1, a1 + n + 1);
for(int i = 1; i <= n; ++i)
if(a1[i] != a[i]) scnt++;
if(scnt <= 2) printf("YES");
else printf("NO");
return 0;
}