题目:
time limit per test
1.5 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output
You are given a sequence aa consisting of nn integers a1,a2,…,ana1,a2,…,an, and an integer xx. Your task is to make the sequence aa sorted (it is considered sorted if the condition a1≤a2≤a3≤⋯≤ana1≤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 ii such that 1≤i≤n1≤i≤n and ai>xai>x, and swap the values of aiai and xx.
For example, if a=[0,2,3,5,4]a=[0,2,3,5,4], x=1x=1, the following sequence of operations is possible:
- choose i=2i=2 (it is possible since a2>xa2>x), then a=[0,1,3,5,4]a=[0,1,3,5,4], x=2x=2;
- choose i=3i=3 (it is possible since a3>xa3>x), then a=[0,1,2,5,4]a=[0,1,2,5,4], x=3x=3;
- choose i=4i=4 (it is possible since a4>xa4>x), then a=[0,1,2,3,4]a=[0,1,2,3,4], x=5x=5.
Calculate the minimum number of operations you have to perform so that aa becomes sorted, or report that it is impossible.
Input
The first line contains one integer tt (1≤t≤5001≤t≤500) — the number of test cases.
Each test case consists of two lines. The first line contains two integers nn and xx (1≤n≤5001≤n≤500, 0≤x≤5000≤x≤500) — the number of elements in the sequence and the initial value of xx.
The second line contains nn integers a1a1, a2a2, ..., anan (0≤ai≤5000≤ai≤500).
The sum of values of nn over all test cases in the input does not exceed 500500.
Output
For each test case, print one integer — the minimum number of operations you have to perform to make aa sorted, or −1−1, if it is impossible.
Example
input
Copy
6 4 1 2 3 5 4 5 6 1 1 3 4 4 1 10 2 2 10 11 9 2 10 12 11 5 18 81 324 218 413 324
output
Copy
3 0 0 -1 1 3
题意:给定一个数x, 可以序列中替换一个比他大的数,使整个序列变成递增序列。
解题思路:可以先从前往后扫一遍,当前面那个数比当前这个数大的话说明要交换,而最少的交换次数应该是序列中刚好比x大的位置开始。值得注意的是,如果当前的数前面有两个比他大的数是无法做到递增序列的,因为无论替换前面至少有一个数始终比当前这个数大,还有,替换到最后的数必须是前一个数,即a[i - 1], 如果不是说明前面至少有一个数和a[i - 1]一样大。(没注意这个wa了好几次),当然其实只用一个变量记录也行,毕竟这个转移只和前面那个变量有关。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
using namespace std;
#define ll long long
const int N = 530;
const int mod = 1e9+7;
int n, m, k, t;
int a[N], b[N];
int dp[N];
void solve(){
int n, x;
cin >> n >> x;
for (int i = 1; i <= n; i ++) cin >> a[i];
memset(dp, 0, sizeof dp);
int pos = 0; a[0] = x;
for (int i = 2; i <= n; i ++){
dp[i] = dp[i - 1];
if (a[i] < a[i - 1]){
for (int j = pos + 1; j < i; j ++)
if (a[pos] < a[j]) {
if (a[pos] > a[i]) {
puts("-1");
return;
}
pos = j, dp[i]++;
}
if (pos != i - 1) {
puts("-1");
return;
}
}
}
printf("%d\n", dp[n]);
}
int main(){
cin >> t;
while (t --) solve();
return 0;
}