#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int a, n, k, x, p, y, w;
int tab[500010];
int T[500010];
int main(){
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> n >> k;
a=1;
while (n>0){
cin >> tab[a];
a++;
n--;
}
n=0;
a=1;
while (a<=k){
if (T[tab[a]]==1){
y=a;
while (T[tab[a]]==1&&tab[a]!=0){
a++;
if (tab[a]==0){
w=1;
}
}
while (a>y){
x=tab[a];
tab[a]=tab[a-1];
tab[a-1]=x;
a--;
n++;
}
T[tab[a]]=1;
}
else {
T[tab[a]]=1;
}
a++;
}
if (w==1){
cout << -1;
}
else {
cout << 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 59 60 61 62 63 64 65 66 67 | #include <bits/stdc++.h> using namespace std; typedef long long ll; int a, n, k, x, p, y, w; int tab[500010]; int T[500010]; int main(){ cin.tie(0); ios_base::sync_with_stdio(0); cin >> n >> k; a=1; while (n>0){ cin >> tab[a]; a++; n--; } n=0; a=1; while (a<=k){ if (T[tab[a]]==1){ y=a; while (T[tab[a]]==1&&tab[a]!=0){ a++; if (tab[a]==0){ w=1; } } while (a>y){ x=tab[a]; tab[a]=tab[a-1]; tab[a-1]=x; a--; n++; } T[tab[a]]=1; } else { T[tab[a]]=1; } a++; } if (w==1){ cout << -1; } else { cout << n; } } |
English