TPOI-2A
upd:粘错代码了,对不起大家。
官方题解。
要使
我们需要让
时间复杂度
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+2;
int a[N];
int main(){
int t;cin>>t;
while(t--){
int n,k;cin>>n>>k;
for(int i=1; i<=n; i++) cin>>a[i];
sort(a+1,a+1+n);
unsigned long long sum=0;bool ok=1;
for(int i=1; i<=n; i++){
if(a[i]==k) sum++,a[i]--;
if(a[i]<=0){
ok=0;
break;
}
if(a[i]>k) break;
}
if(!ok){
cout<<"-1\n";
continue;
}
ok=0;
int kk=0;
if(k==1){
cout<<"0\n";
continue;
}
for(int i=1; i<=n; i++){
if(a[i]==kk) continue;
kk++;sum+=a[i]-kk;
if(kk==k-1){
cout<<sum<<"\n";
ok=1;break;
}
}
if(!ok) cout<<"-1\n";
}
return 0;
}