I am trying to solve this problem : replace X
This is the solution that I have come up with
#include<iostream>
#include<algorithm>
#define ll long long int
using namespace std;
int main(){
ll t;
cin>>t;
while(t--){
ll n,x,p,k;
cin>>n>>x>>p>>k;
int a[n];
bool xext = false;
for(ll i=0; i<n; i++){
cin>>a[i];
if(a[i] == x){
xext = true;
}
}
sort(a,a+n);
if(!xext){
a[k-1] = x;
sort(a,a+n);
}
ll ans = 0;
if(a[p-1] == x){
ans = 0;
}
else{
if(k == p){
if(x<a[p-1]){
for(ll i=p-1; i>=0&&a[i]>x; i--){ans++;}
}
else{
for(ll i=p-1; i<n&&a[i]<x; i++){ans++;}
}
}
else if(k<p){
if(x<a[p-1]){
ans = -1;
}
else{
for(ll i=p-1; i<n&&a[i]<x; i++){ans++;}
}
}
else{
if(x>a[p-1]){
ans = -1;
}
else{
for(ll i=p-1; i>=0&&a[i]>x; i--){ans++;}
}
}
}
cout<<ans<<endl;
}
return 0;
}
On submitting its showing wrong answer
can you explain me what am I doing wrong here