Educational Codeforces Round 99 (Rated for Div. 2) D

Educational Codeforces Round 99 (Rated for Div. 2) D

大意

略...

思路

首先,若原序列有序,那么此时交换次数为 \(0\)

否则,\(x\) 必进行交换。

考虑从头开始的连续的小于等于 \(x\) 的一段(即从头开始的每个数都小于等于 \(x\) 的连续子序列),显然此段内一定要有序,否则因为 \(x\) 只能与比自己大的数字交换,无法通过交换使之有序。

考虑另一段。

首先, 如果有序,结束,否则,

\(x\) 必与大于 \(x\) 的第一个数交换,否则当 \(x\) 与后面先行交换后显然无法让序列单调。

此时问题转化为了对于一个新的 \(x\) ,求最少次数,然后就可以以上述思路递推处理。

代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;

#define ll long long
#define ull unsigned long long
#define cint const int&
#define Pi acos(-1)

const int mod = 998244353;
const int inf_int = 0x7fffffff;
const ll inf_ll = 0x7fffffffffffffff;
const double ept = 1e-9;

int t, n, x;
int a[505], b[505];

bool check(int i) {
    for(; i<=n; i++)
        if(a[i] < a[i-1]) return 0;
    return 1;
}

int main() {
    cin >> t;
    while(t--) {
        bool flag=0;
        a[0] = -1;
        cin >> n >> x;
        for(int i=1; i<=n; i++) {
            cin >> a[i];
            if(a[i] < a[i-1]) flag=1;
        }
        if(!flag) {cout << 0 << endl; continue;}

        int ans=0;
        for(int i=1; i<=n && !check(i); i++) {
            if(a[i] > x) swap(a[i], x), ++ans;
            if(a[i] < a[i-1]) flag=0;
        }
        if(!flag) cout << -1 << endl;
        else cout << ans << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值