Educational Codeforces Round 99_D. Sequence and Swaps

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 𝑥.

这个数据大小就摆明了是在说快来暴力我!快来!

就模拟,就嗯模。

  1. 将x插入数组a;
  2. 对新数组进行排序;
  3. 通过结果反推次序;
  4. 判断不可能情况。

不一定用严格按照排序后的序列排序,某次操作后也许已经满足了非递减的条件。

代码:

#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的题目确实不难啊。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值