D. Sequence and Swaps
题意解析:
序列数组a和x,每次可以将序列中一个比x大的数拿出来和x交换,问最少操作几次可以使数组a变成非递减序列,如果不可能输出-1。
The first line contains two integers 𝑛 and 𝑥 (1≤𝑛≤500, 0≤𝑥≤500) — the number of elements in the sequence and the initial value of 𝑥.
这个数据大小就摆明了是在说快来暴力我!快来!
就模拟,就嗯模。
- 将x插入数组a;
- 对新数组进行排序;
- 通过结果反推次序;
- 判断不可能情况。
不一定用严格按照排序后的序列排序,某次操作后也许已经满足了非递减的条件。
代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
typedef long long ll;
const ll mod = 1e9 + 7;
using namespace std;
const int N = 1e3 + 5;
int a[N], aa[N];
int T, n, x;
bool check(int x) {
for (int i = x; i <= n; i++) {
if (a[i] < a[i - 1]) return false;
//非递减
}
return true;
}
int main() {
cin >> T;
while (T--) {
bool flag = 1;
bool f = 1;
cin >> n >> x;
for (int i = 1; i <= n; i++) {
cin >> a[i];
aa[i] = a[i];
}
for (int i = 2; i <= n; i++) {
if (a[i] < a[i - 1]) f = 0;
//是否原数组就满足条件
}
aa[n + 1] = x;
sort(aa + 1, aa + n + 2);
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (a[i] != aa[i])
//原数组里第i个需要和x 交换
{
if (a[i] > x)
//比x大可交换
{
swap(a[i], x);
cnt++;
} else
//不可交换
flag = false;
}
if (check(i)) break;
//之后i~n满足数组约束条件,不需要x继续交换
}
if (f) cout << 0 << endl;
else {
if (flag) cout << cnt << endl;
else cout << -1 << endl;
}
}
}
/*
皮卡丘冲鸭!
へ /|
/\7 ∠_/
/ │ / /
│ Z _,< / /`ヽ
│ ヽ / 〉
Y ` / /
イ ● 、 ● ⊂⊃〈 /
() へ | \〈
>ー 、_ ィ │ //
/ へ / ノ<| \\
ヽ_ノ (_/ │//
7 |/
>―r ̄ ̄`ー―_
*/
/*
_ooOoo_
o8888888o
88" . "88
(| -_- |)
O\ = /O
____/`---'\____
.' \\| |// `.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\-/'' | |
\ .-\__ `-` ___/-. /
___`. .' /-.-\ `. . __
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `-. \_ __\ /__ _/ .-` / /
======`-.____`-.___\_____/___.-`____.-'======
`=-='
*/
这次Div2的题目确实不难啊。