#include<bits/stdc++.h>
using namespace std;
const int N=5e5+6;
bool wyst[N],wyst2[N],tab[N];
int main()
{
ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n,k;cin>>n>>k;
int check=0;
for(int i=1;i<=n;i++)
{
int a;cin>>a;
if(i<=k)
{
if(wyst[a])
{
tab[i-1]=1;
check++;
}
wyst[a]=1;
}
else
{
if(wyst[a]==0&&wyst2[a]==0)
{
check--;
tab[i-1]=1;
}
wyst2[a]=1;
}
}
if(check>0)
{
cout<<-1<<"\n";
return 0;
}
int a=0;
long long res=0;
long long c=0;
for(int i=k-1;i>=0;i--)
{
if(!tab[i])continue;
long long d=k-i-a;
a++;c++;
res+=d;
}
a=0;
res+=c*c;
for(int i=k;i<n;i++)
{
if(!c)break;
if(!tab[i])continue;
long long d=i-k-a-1;
c--;a++;
res+=d;
}
cout<<res<<"\n";
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | #include<bits/stdc++.h> using namespace std; const int N=5e5+6; bool wyst[N],wyst2[N],tab[N]; int main() { ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0); int n,k;cin>>n>>k; int check=0; for(int i=1;i<=n;i++) { int a;cin>>a; if(i<=k) { if(wyst[a]) { tab[i-1]=1; check++; } wyst[a]=1; } else { if(wyst[a]==0&&wyst2[a]==0) { check--; tab[i-1]=1; } wyst2[a]=1; } } if(check>0) { cout<<-1<<"\n"; return 0; } int a=0; long long res=0; long long c=0; for(int i=k-1;i>=0;i--) { if(!tab[i])continue; long long d=k-i-a; a++;c++; res+=d; } a=0; res+=c*c; for(int i=k;i<n;i++) { if(!c)break; if(!tab[i])continue; long long d=i-k-a-1; c--;a++; res+=d; } cout<<res<<"\n"; } |
English