Educational Codeforces Round 99------Sequence and Swaps

题目

You are given a sequence a consisting of n integers a1,a2,…,an, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a1≤a2≤a3≤⋯≤an holds).

To make the sequence sorted, you may perform the following operation any number of times you want (possibly zero): choose an integer i such that 1≤i≤n and ai>x, and swap the values of ai and x.

For example, if a=[0,2,3,5,4], x=1, the following sequence of operations is possible:

choose i=2 (it is possible since a2>x), then a=[0,1,3,5,4], x=2;
choose i=3 (it is possible since a3>x), then a=[0,1,2,5,4], x=3;
choose i=4 (it is possible since a4>x), then a=[0,1,2,3,4], x=5.
Calculate the minimum number of operations you have to perform so that a becomes sorted, or report that it is impossible.

题意

给你一个数组和一个数字x,用x从数组里面换数,交换的同时交换数组元素值和x,问使数组变成上升有序数组最少需要几步。如果不能则输出-1

题解

模拟就可以,将原数组克隆填入x排序,然后对比原数组与排序后数组,元素相同时跳过下一个,不相同判断能否进行交换,此处注意,每次交换后x都会越来越大,如果交换后不能满足当前元素大于等于上一个元素,则无解

AC代码

#include<iostream>
#include<cstdio>
#include<string>
#include<queue>
#include<stack>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
using namespace std;
#define ll long long
const int N = 1e5 + 15;
void closeStd() {
	std::ios::sync_with_stdio(false);
	std::cin.tie(0);
	std::cout.tie(0);
}
int main()
{
	closeStd();
	int t; cin >> t;
	while (t--) {
		int n, x; cin >> n >> x;
		int a[505], b[505];
		a[0] = 0;
		int f = 0;
		for (int i = 1; i <= n; i++) {
			cin >> a[i];
			b[i] = a[i];
			if (a[i] < a[i - 1])
				f = 1;
		}
		if (f == 0) {
			cout << 0 << endl;
			continue;
		}
		a[n + 1] = x;
		sort(a + 1, a + 1 + n + 1);
		int cnt = 0, flag = 0;
		for (int i = 1; i <= n; i++) {
			if (a[i] == b[i])
				continue;
			else {
				if (b[i] > x)
					swap(b[i], x), cnt++;
				else
					flag = 1;
				if (b[i] < b[i - 1])
					flag = 1;
			}
			int ff = 0;
			for (int j = i; j <= n; j++) {
				if (b[j] < b[j - 1]) {
					ff = 1;
					break;
				}
			}
			if (!ff)
				break;
		}
		if (flag)
			cout << -1 << endl;
		else
			cout << cnt << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值