D. Sequence and Swaps
time limit per test1.5 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard output
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.
Input
The first line contains one integer t (1≤t≤500) — the number of test cases.
Each test case consists of two lines. The first line contains two integers n and x (1≤n≤500, 0≤x≤500) — the number of elements in the sequence and the initial value of x.
The second line contains n integers a1, a2, …, an (0≤ai≤500).
The sum of values of n over all test cases in the input does not exceed 500.
Output
For each test case, print one integer — the minimum number of operations you have to perform to make a sorted, or −1, if it is impossible.
Example
inputCopy
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
outputCopy
3
0
0
-1
1
3
题意:为求让数组有序需要的最小操作数,可进行的操作是当ai>x时候互换ai与x。
解题思路:
1.因为我是从左往右开始操作,所以当到ai时候,若ai以后的数列是有序的,则不需要继续进行操作,因此我开了一个数组记录后面的序列是否有序,dp[i]既表示>=i时的数列是有序的。(此步看不懂先看第二步,后面有介绍作用)
2.从左开始,根据贪心的思想,为保证有序左面的数要尽可能的小,因此当ai>x时候,我们要将ai与x互换,这样的操作是合理的,如果这样操作下来,无法使数列有序,那么就是无法进行有序排列的,就输出-1,否则输出交换次数
3.但我们会想到,如果明明是有序的但是因为ai比x大就进行交换是多余的,所以dp数组就有作用了,当>=i时,数列有序则直接跳出,不会进行多余的交换,而i之前是无序的,则i之前的以小换大就有利于<i时候数列的有序。
ac代码如下:
下面展示一些 内联代码片
。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
bool dp[505]={false};
int main()
{
int t;
int an[505];
cin>>t;
while(t--){
memset(an,0,sizeof(an));
memset(dp,0,sizeof(dp));
int n;
int x;
cin>>n;
cin>>x;
int ans=0;
for(int i=0;i<n;i++){
cin>>an[i];
}
dp[n-1]=1;
for(int i=n-2;i>=0;i--){
if(an[i]<=an[i+1]){
dp[i]=true;
}
else{
dp[i]=false;
break;
}
}
//for(int i=0;i<n;i++) cout<<dp[i]<<endl;
if(dp[0]) cout<<"0"<<endl;
else{
for(int i=0;i<n;i++){
if(i>0&&dp[i]&&an[i]>an[i-1]){
break;
}
else{
if(an[i]>x){
int t=an[i];
an[i]=x;
x=t;
ans++;
}
}
}
bool f2=false;
for(int i=1;i<n;i++){
if(an[i]-an[i-1]<0){
cout<<"-1"<<endl;
f2=true;
break;
}
}
if(!f2) cout<<ans<<endl;
}
}
}