Problem:
Robot Arm
PCK Industry is developing a new robot arm. The task of this robot arm is to sort $N$ parts assigned numbers from 1 to $N$ in a single row, in order of decreasing number.
The robot arm can select three parts in one operation (they do not have to be next to each other) and perform the following exchange operations on them.
When the selected parts are numbered a, b, and c from the beginning, swap the positions of these parts in the order b, c, a or c, a, b.
For example, if the parts are lined up as 3 6 1 5 4 2 and the robot arm selects the part with 6 5 4, these positions can be swapped and rearranged in the order 3 5 1 4 6 2 or 3 4 1 6 5 2.
Write a program which reads a sequence of parts and finds the minimum number of operations of the robot arm required to sort them in the order of decreasing number. If it is not possible to sort the parts in decreasing order no matter how the operations are performed, output -1.
Input
The input is given in the following format.
$N$
$h_1$ $h_2$ ... $h_N$
The first line gives the number of parts $N$ ($3 \leq N \leq 200,000$). The second line gives the number of each part $h_i$ ($1 \leq h_i \leq N$). All numbers are different (if $i \ne j$, then $h_i \ne h_j$)
Output
Output the minimum number of operations in a line. If the numbers cannot be sorted in decreasing order, output
-1
.
Sample Input and Output
Sample Input 1
6
2 3 4 1 6 5
Sample Output 1
3
Sample Input 2
4
2 3 4 1
Sample Output 2
-1

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
#define ll long long
using namespace std;

class DSU
{
	vector<int> parent, sz;

public:
	DSU(const int size) : parent(size, -1),sz(size,1) {};
	int find(const int a)
	{
		return parent[a] < 0 ? a : parent[a] = find(parent[a]);
	}
	int groupSize(const int a)
	{
		return sz[find(a)];
	}
	void merge(int a, int b)
	{
		a = find(a);
		b = find(b);
		if (a == b)
			return;
		if (parent[a] > parent[b])
			swap(a, b);
		sz[a] += sz[b];
		parent[b] = a;
	}
};
int main()
{
	int n;
	cin >> n;
	vector<int> permutation(n);
	for (auto &p : permutation)
	{
		cin >> p;
		--p;
	}
	DSU dsu(n);
	for (auto i = 0; i < n; ++i)
	{
		dsu.merge(i, permutation[i]);
	}
	int count=0;
	int even_count=0;
	for (auto i = 0; i < n; ++i)
	{
		if (dsu.find(i) != i)
			continue;
		if (dsu.groupSize(i) % 2 == 0)
			even_count ++;
		count += dsu.groupSize(i) >> 1;
	}
	if (even_count%2 == 0)
		cout << count << '\n';
	else
		cout << "-1\n";
}
accuracy: 1
time_ms: 30
memory_kb: 5464
final_rank: 12

code_snippet: #include <bits/stdc++.h>

int main() {
    int N;
    std::cin >> N;
    std::vector<int> H(N);
    for (auto& h : H) {
        std::cin >> h;
        h--;
    }
    std::vector<int> I(N);
    for (int i{} ; i < N ; i++) I[H[i]] = i;
    std::vector<bool> vis(N);
    int ans{}, even{};
    for (int i{} ; i < N ; i++) if (!vis[i] and i != H[i]) {
        // std::cout << "hello " << i << std::endl;
        int num{1};
        vis[i] = true;
        for (int cur{H[i]} ; cur != i ; cur = H[cur]) {
            num++;
            assert(vis[cur] == false);
            vis[cur] = true;
        }
        even += (num % 2 == 0);
        ans += num / 2;
    }
    std::cout << (even % 2 ? -1 : ans) << '\n';
}
accuracy: 1
time_ms: 30
memory_kb: 4696
final_rank: 10

code_snippet: #include <bits/stdc++.h>

int main() {
    int n;
    std::cin >> n;
    std::vector<int> p(n);
    for (int i = 0; i < n; i++) std::cin >> p[i];
    for (int i = 0; i < n; i++) p[i]--;
    int ans = 0;
    std::vector<bool> used(n);
    int even = 0;
    for (int i = 0; i < n; i++) {
        if (used[i]) continue;
        int size = 0;
        int cur = i;
        while (!used[cur]) {
            size++;
            used[cur] = true;
            cur = p[cur];
        }
        if (size == 1) continue;
        if (size % 2 == 0) {
            even++;
            ans += (size - 2) / 2;
        } else {
            ans += (size - 1) / 2;
        }
    }
    if (even % 2 == 0) {
        ans += even;
    } else {
        ans = -1;
    }
    std::cout << ans << '\n';
}
accuracy: 1
time_ms: 30
memory_kb: 3872
final_rank: 8

code_snippet: #include<bits/stdc++.h>
#define overload(a,b,c,d,...) d
#define rep1(a) for(ll _=0;_<a;++_)
#define rep2(i,a) for(ll i=0;i<a;++i)
#define rep3(i,a,b) for(ll i=a;i<b;++i)
#define rep(...) overload(__VA_ARGS__,rep3,rep2,rep1)(__VA_ARGS__)
#define rrep1(i,a) for(ll i=(ll)a-1;i>=0;--i)
#define rrep2(i,a,b) for(ll i=(ll)b-1;i>=(ll)a;--i)
#define rrep(...) overload(__VA_ARGS__,rrep2,rrep1)(__VA_ARGS__)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define eb emplace_back
#define pb push_back
using namespace std;
using ll=long long;
using ull=unsigned long long;
using ld=long double;
template<typename T,typename U>inline bool chmin(T&a,const U&b){return (a>b?a=b,true:false);}
template<typename T,typename U>inline bool chmax(T&a,const U&b){return (a<b?a=b,true:false);}
static constexpr ll inf=numeric_limits<ll>::max()/2;
int main(){
    ll n;cin>>n;
    vector<ll>h(n);
    for(auto&e:h)cin>>e;
    for(auto&e:h)e--;
    vector<ll>vis(n,0);
    ll cnt=0;
    ll ans=0;
    rep(i,n)if(!vis[i]){
        ll sz=0;
        ll now=i;
        while(!vis[now]){
            vis[now]=1;
            now=h[now];
            sz++;
        }
        if(sz%2)ans+=sz/2;
        else ans+=sz/2-1,cnt++;
    }
    if(cnt%2==0)ans+=cnt;
    else ans=-1;
    cout<<ans<<endl;
}
accuracy: 1
time_ms: 30
memory_kb: 6324
final_rank: 13

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<int(n);i++)

constexpr int inf=1e9+10;
constexpr char newl='\n';
constexpr int dx[]={0,1,0,-1};
constexpr int dy[]={1,0,-1,0};
using ll=long long;

bool valid(int i,int j,int h,int w){
    return 0<=i && i<h && 0<=j && j<w;
}

template<typename T>
bool chmin(T &a,T b){
    return b<a ? a=b,true:false;
}

int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);

    int n;
    cin >> n;
    vector<int> p(n);
    rep(i,n)cin >> p[i],p[i]--;

    vector<bool> al(n,false);
    int ans=0;
    vector<int> ev_sz;
    rep(i,n)if(!al[i]){
        int j=i;
        int sz=1;
        al[j]=true;
        while(!al[p[j]]){
            sz++;
            j=p[j];
            al[j]=true;
        }
        if(sz%2==0)ev_sz.emplace_back(sz);
        ans+=sz/2;
    }
    if(ev_sz.size()%2==1)cout << -1 << endl;
    else cout << ans << endl;
}
accuracy: 1
time_ms: 10
memory_kb: 4404
final_rank: 2

code_snippet: #include <bits/stdc++.h>
#define rep(i, n) for(int i = 0; i < (n); i++)
#define vi vector<int>
#define pii pair<int,int>
#define pll pair<ll,ll>
using namespace std;
using ll = long long;


int main(){
	int n;
	cin >> n;
	vi h(n);
	rep(i, n){
		cin >> h[i];
		h[i]--;
	}
	vi used(n);
	int ans = 0;
	int evens = 0;
	rep(i, n) if(!used[i]){
		used[i] = 1;
		int pos = h[i];
		int cnt = 1;
		while(pos != i){
			used[pos] = 1;
			pos = h[pos];
			cnt++;
		}
		if(!(cnt & 1)) evens++;
		ans += cnt / 2;
	}
	if(evens & 1) cout << "-1\n";
	else cout << ans << "\n";
}
accuracy: 1
time_ms: 30
memory_kb: 4692
final_rank: 9

code_snippet: /* -*- coding: utf-8 -*-
 *
 * 0448.cc: Robot Arm
 */

#include<cstdio>
#include<algorithm>
#include<utility>
 
using namespace std;

/* constant */

const int MAX_N = 200000;

/* typedef */

typedef long long ll;
typedef pair<int,int> pii;

/* global variables */

int hs[MAX_N], ps[MAX_N];
pii his[MAX_N], tmp[MAX_N];
bool used[MAX_N];

/* subroutines */

template <typename T>
ll merge_sort(T as[], T tmp[], int l, int r) { // [l, r)
  ll ic = 0;

  if (l + 1 < r) {
    int m = (l + r) / 2;
  
    ic = merge_sort(as, tmp, l, m) + merge_sort(as, tmp, m, r);

    int i = l, j = m, k = l;

    while (i < m && j < r) {
      if (as[i] <= as[j]) tmp[k++] = as[i++];
      else tmp[k++] = as[j++], ic += m - i;
    }

    while (i < m) tmp[k++] = as[i++];
    while (j < r) tmp[k++] = as[j++];

    for (int i = l; i < r; i++) as[i] = tmp[i];
  }  

  return ic;
}

/* main */

int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", hs + i);

  for (int i = 0; i < n; i++) his[i] = pii(hs[i], i);
  ll ic = merge_sort(his, tmp, 0, n);
  if (ic & 1) { puts("-1"); return 0; }

  for (int i = 0; i < n; i++) ps[his[i].second] = i;
  //for (int i = 0; i < n; i++) printf("%d ", ps[i]); putchar('\n');

  int sum = 0;
  for (int st = 0; st < n; st++)
    if (! used[st]) {
      int l = 0;
      for (int u = st; ! used[u]; u = ps[u]) l++, used[u] = true;
      sum += l / 2;
    }

  printf("%d\n", sum);
  return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 7820
final_rank: 5

code_snippet: #include <stdio.h>
#include <math.h>
#include <iostream>
#include <iomanip>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
#define rep(i, n) for (int i = 0; i < n; i++)
#define endl '\n'
#define print(n) cout << (n) << endl
int main()
{
    int n;
    cin >> n;
    vector<int> a(n);
    vector<bool> t(n);
    rep(i, n) cin >> a[i], a[i]--;
    int ans = 0;
    bool s = true;
    rep(i, n)
    {
        if (t[i]) continue;
        int id = i, c = 0;
        do
        {
            t[id] = true;
            id = a[id];
            c++;
        } while (!t[id]);
        ans += c >> 1;
        s ^= !(c & 1);
    }
    print(s ? ans : -1);
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3828
final_rank: 6

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    // https://codeforces.com/contest/1591/problem/D
    int q = 1;
    while(q--){
        int n; cin >> n;
        vector<int> a(n);
        for(int i=0;i<n;i++){
            cin >> a[i];
        }
        vector<int> v = a;
        sort(v.begin(), v.end());
        // 本来iにあるべき要素が今どこにあるか
        vector<int> idx(n);
        for(int i=0;i<n;i++){
            idx[lower_bound(v.begin(), v.end(), a[i]) - v.begin()] = i;
            a[i] = lower_bound(v.begin(), v.end(), a[i]) - v.begin();
        }
        int res = 0;
        int rev = 0;
        for(int _i=n-1;_i>=0;_i--){
            if(idx[_i] == _i) continue;
            if(idx[_i] == a[_i]){
                rev++;
                int i = idx[_i];
                int j = a[_i];
                swap(a[i], a[j]);
                idx[i] = i;
                idx[j] = j;
                continue;
            }
            // i→j j→k k→i
            int i = idx[_i];
            int j = _i;
            int k = a[_i];
            swap(a[i], a[j]);
            swap(a[i], a[k]);
            idx[a[i]] = i;
            idx[a[j]] = j;
            idx[a[k]] = k;
            res++;
        }
        if(rev%2 == 0){
            cout << res+rev << "\n";
        }
        else{
            cout << -1 << "\n";
        }
    }
}
accuracy: 1
time_ms: 50
memory_kb: 5480
final_rank: 16

code_snippet: #pragma GCC optimize("Ofast")
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <queue>
#include <cstdio>
#include <ctime>
#include <assert.h>
#include <chrono>
#include <random>
#include <numeric>
#include <set>
#include <deque>
#include <stack>
#include <sstream>
#include <utility>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <tuple>
#include <array>
#include <bitset>
using namespace std;
typedef long long int ll;
typedef unsigned long long ull;

mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
ll myRand(ll B) {
    return (ull)rng() % B;
}
inline double time() {
    return static_cast<double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}

int main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    // https://codeforces.com/contest/1591/problem/D
    int q = 1;
    while(q--){
        int n; cin >> n;
        vector<int> a(n);
        for(int i=0;i<n;i++){
            cin >> a[i];
        }
        vector<int> v = a;
        sort(v.begin(), v.end());
        // 本来iにあるべき要素が今どこにあるか
        vector<int> idx(n);
        for(int i=0;i<n;i++){
            idx[lower_bound(v.begin(), v.end(), a[i]) - v.begin()] = i;
            a[i] = lower_bound(v.begin(), v.end(), a[i]) - v.begin();
        }
        int res = 0;
        int rev = 0;
        for(int _i=n-1;_i>=0;_i--){
            if(idx[_i] == _i) continue;
            if(idx[_i] == a[_i]){
                rev++;
                int i = idx[_i];
                int j = a[_i];
                swap(a[i], a[j]);
                idx[i] = i;
                idx[j] = j;
                continue;
            }
            // i→j j→k k→i
            int i = idx[_i];
            int j = _i;
            int k = a[_i];
            swap(a[i], a[j]);
            swap(a[i], a[k]);
            // cout << a[0] << " " << a[1] << " " << a[2] << endl;
            idx[a[i]] = i;
            idx[a[j]] = j;
            idx[a[k]] = k;
            res++;
        }
        if(rev%2 == 0){
            cout << res+rev << "\n";
        }
        else{
            cout << -1 << "\n";
        }
    }
}
accuracy: 1
time_ms: 50
memory_kb: 5456
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
const long long mod1 = 1000000007;
const long long mod2 = 998244353;
double pi = 3.141592653589;
using ll = long long;
vector<ll> dx = {-1,0,1,0,1,1,-1,-1};
vector<ll> dy = {0,1,0,-1,1,-1,1,-1};
vector<char> abc = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
vector<char> ABC = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
 
struct UnionFind{
    vector<ll> par, siz;
    
    UnionFind(ll n):par(n,-1),siz(n,1){}
    
    ll root(ll x){//親を返す
        if(par[x] == -1) return x;
        else return par[x] = root(par[x]);
    }
    
    bool issame(ll x,ll y){//同じグループかどうか
        return root(x) == root(y);
    }
    
    bool unite(ll x, ll y){//合体
        x = root(x); y = root(y);
        if(x == y) return false;
        if(siz[x] < siz[y]) swap(x,y);
        par[y] = x;
        siz[x] += siz[y];
        return true;
    }
    
    ll size(ll x){//xがいるグループのサイズ
        return siz[root(x)];
    }
    
    
    
};
 
long long pow2(long long x,long long n){
    long long ans = 1;
    while(n != 0){
        long long a = x;
        long long z = 1;
        while(z*2 <= n){
            a *=a;
            a=a%mod2;
            z*=2;
        }
        ans*=a;
        ans=ans%mod2;
        n-=z;
    }
    return ans; 
}//累乗 x^n
 
template<typename T>
void input_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        cin >> A.at(i);
    }
    return;
}//入力を配列で受け取る
 
template<typename T>
void output_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        if(i != 0){
            cout << " ";
        }
        cout << A.at(i);
    }
    cout << endl;
    return;
}//配列を出力
 
template<typename T>
long long count_x(vector<T> &A,T x){
    long long counter = 0;
    for(int i = 0; i < (int)A.size(); i++){
        if(A.at(i) == x){
            counter++;
        }
    }
    return counter;
}//配列内のxの個数をreturn
 
template<typename T>
long long duplicate(vector<T> &A){
    ll ans = 0;
    ll N = A.size();
    T a = A.at(0);
    for(int i = 1; i < N; i++){
        if(a == A.at(i)) ans++;
        else a = A.at(i);
    }
    return ans;
}
 
template<typename T>
void chmin(T &a,T b){
    if(a>b){
        a = b;
    }
    return;
}
 
template<typename T>
void chmax(T&a,T b){
    if(a < b){
        a = b;
    }
    return;
}

/*
絶対値   abs()
配列の要素の追加   push_back() 
char→intに変換   -'0'
string→intに変換   atoi(文字列名.c_str())
配列の中身をN個の０で初期化   配列名.resize(N)
配列の中身をN個のaで初期化   配列名.assign(N,a)
配列の中からK以上の数字の最小値を出力　lower_bound(配列.begin(),配列.end(),K)
入力scanf("%lld %lld",&a,&b) みたいな感じ &を忘れずに
小数の桁数設定cout << fixed << setprecision(桁数);
*/


int main(){
    ll N; cin >> N;
    vector<ll> h(N);
    input_vec(h);
    UnionFind uf(N);
    vector<vector<ll>> count(N);
    vector<vector<ll>> li;
    for (int i = 0; i < N; i++) h[i]--;
    for(int i = 0; i < N; i++){
        uf.unite(i,h[i]);
    }
    for(int i = 0; i < N; i++){
        count[uf.root(i)].push_back(i);
    }
    for(int i = 0; i < N; i++){
        if((int)count[i].size() == 0) continue;
        li.push_back(count[i]);
    }
    
    ll ans = 0;
    ll count2 = 0;
    for(auto a: li){
        if((int)a.size()%2 == 0) count2++;
        ans+=((int)a.size()-1)/2;
    } 
    if(count2%2 == 0) cout << count2+ans << endl;
    else cout << -1 << endl;
    
    
}
accuracy: 1
time_ms: 50
memory_kb: 31004
final_rank: 18

code_snippet: #include <bits/stdc++.h>
using namespace std;
const long long mod1 = 1000000007;
const long long mod2 = 998244353;
double pi = 3.141592653589;
using ll = long long;
vector<ll> dx = {-1,0,1,0,1,1,-1,-1};
vector<ll> dy = {0,1,0,-1,1,-1,1,-1};
vector<char> abc = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
vector<char> ABC = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
 
struct UnionFind{
    vector<ll> par, siz;
    
    UnionFind(ll n):par(n,-1),siz(n,1){}
    
    ll root(ll x){//親を返す
        if(par[x] == -1) return x;
        else return par[x] = root(par[x]);
    }
    
    bool issame(ll x,ll y){//同じグループかどうか
        return root(x) == root(y);
    }
    
    bool unite(ll x, ll y){//合体
        x = root(x); y = root(y);
        if(x == y) return false;
        if(siz[x] < siz[y]) swap(x,y);
        par[y] = x;
        siz[x] += siz[y];
        return true;
    }
    
    ll size(ll x){//xがいるグループのサイズ
        return siz[root(x)];
    }
    
    
    
};
 
long long pow2(long long x,long long n){
    long long ans = 1;
    while(n != 0){
        long long a = x;
        long long z = 1;
        while(z*2 <= n){
            a *=a;
            a=a%mod2;
            z*=2;
        }
        ans*=a;
        ans=ans%mod2;
        n-=z;
    }
    return ans; 
}//累乗 x^n
 
template<typename T>
void input_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        cin >> A.at(i);
    }
    return;
}//入力を配列で受け取る
 
template<typename T>
void output_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        if(i != 0){
            cout << " ";
        }
        cout << A.at(i);
    }
    cout << endl;
    return;
}//配列を出力
 
template<typename T>
long long count_x(vector<T> &A,T x){
    long long counter = 0;
    for(int i = 0; i < (int)A.size(); i++){
        if(A.at(i) == x){
            counter++;
        }
    }
    return counter;
}//配列内のxの個数をreturn
 
template<typename T>
long long duplicate(vector<T> &A){
    ll ans = 0;
    ll N = A.size();
    T a = A.at(0);
    for(int i = 1; i < N; i++){
        if(a == A.at(i)) ans++;
        else a = A.at(i);
    }
    return ans;
}
 
template<typename T>
void chmin(T &a,T b){
    if(a>b){
        a = b;
    }
    return;
}
 
template<typename T>
void chmax(T&a,T b){
    if(a < b){
        a = b;
    }
    return;
}

/*
絶対値   abs()
配列の要素の追加   push_back() 
char→intに変換   -'0'
string→intに変換   atoi(文字列名.c_str())
配列の中身をN個の０で初期化   配列名.resize(N)
配列の中身をN個のaで初期化   配列名.assign(N,a)
配列の中からK以上の数字の最小値を出力　lower_bound(配列.begin(),配列.end(),K)
入力scanf("%lld %lld",&a,&b) みたいな感じ &を忘れずに
小数の桁数設定cout << fixed << setprecision(桁数);
*/
vector<ll> h;
vector<ll> li;
void change(ll a, ll b, ll c){
    swap(h[a],h[b]);
    swap(h[a],h[c]);
    li[h[a]] = a;
    li[h[b]] = b;
    li[h[c]] = c;
    return;
}

int main(){
    ll N; cin >> N;
    h.resize(N);
    li.resize(N);
    input_vec(h);
    ll count = 0;
    ll point = 0;
    vector<pair<ll,ll>> p;
    for(int i = 0; i < N; i++) {
        h[i]--;
        li[h[i]] = i;
    }
    for(int i = 0; i < N; i++) if(li[i] == i) point++;
    for(int i = 0; i < N; i++) if(li[i] == h[i]&&h[i]>i) p.push_back(make_pair(i,h[i]));
    for(int i = 0; point < N-2; i++){
        //cout << "point: " << point << endl;
        ll nh = li[i];
        if(nh == i)continue;
        count++;
        ll a = nh;
        ll b = i;
        ll c = -1;
        if(h[b]!=a){
            //cout << "x" << endl;
            c = h[b];
        }
        else if(b!= li[a]&&li[a] != a){
            c = li[a];
            //cout << "y" << endl;
        }
        else{
            //cout << "c: " << c << endl;
            for(int j = i+1; j < N&&c == -1; j++){
                //cout << "j: " << j <<  endl;
                if(a == j) continue;
                if(b == j) continue;
                if(li[j] == j) continue;
                if(li[j] == h[j])c = j;
            }
            if(c == -1){
                for(int j = N-1; j >= 0; j--){
                    if(li[j] == j) continue;
                    c = j;
                }
            }
        }
        //printf("change %lld %lld %lld\n",a,b,c);
        change(a,b,c);
        if(li[i] != i) change(a,b,c);
        //output_vec(h);
        //output_vec(li);
        if(h[a] == a) point++;
        if(h[b] == b) point++;
        if(h[c] == c) point++;
        
    }
    if(point == N) cout << count << endl;
    else cout << -1 << endl;
    
    
    
    
    
    
    
    
    
    
}
accuracy: 0.84
time_ms: 30
memory_kb: 6196
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
const long long mod1 = 1000000007;
const long long mod2 = 998244353;
double pi = 3.141592653589;
using ll = long long;
vector<ll> dx = {-1,0,1,0,1,1,-1,-1};
vector<ll> dy = {0,1,0,-1,1,-1,1,-1};
vector<char> abc = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
vector<char> ABC = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
 
struct UnionFind{
    vector<ll> par, siz;
    
    UnionFind(ll n):par(n,-1),siz(n,1){}
    
    ll root(ll x){//親を返す
        if(par[x] == -1) return x;
        else return par[x] = root(par[x]);
    }
    
    bool issame(ll x,ll y){//同じグループかどうか
        return root(x) == root(y);
    }
    
    bool unite(ll x, ll y){//合体
        x = root(x); y = root(y);
        if(x == y) return false;
        if(siz[x] < siz[y]) swap(x,y);
        par[y] = x;
        siz[x] += siz[y];
        return true;
    }
    
    ll size(ll x){//xがいるグループのサイズ
        return siz[root(x)];
    }
    
    
    
};
 
long long pow2(long long x,long long n){
    long long ans = 1;
    while(n != 0){
        long long a = x;
        long long z = 1;
        while(z*2 <= n){
            a *=a;
            a=a%mod2;
            z*=2;
        }
        ans*=a;
        ans=ans%mod2;
        n-=z;
    }
    return ans; 
}//累乗 x^n
 
template<typename T>
void input_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        cin >> A.at(i);
    }
    return;
}//入力を配列で受け取る
 
template<typename T>
void output_vec(vector<T> &A){
    ll N = A.size();
    for(int i = 0; i < N; i++){
        if(i != 0){
            cout << " ";
        }
        cout << A.at(i);
    }
    cout << endl;
    return;
}//配列を出力
 
template<typename T>
long long count_x(vector<T> &A,T x){
    long long counter = 0;
    for(int i = 0; i < (int)A.size(); i++){
        if(A.at(i) == x){
            counter++;
        }
    }
    return counter;
}//配列内のxの個数をreturn
 
template<typename T>
long long duplicate(vector<T> &A){
    ll ans = 0;
    ll N = A.size();
    T a = A.at(0);
    for(int i = 1; i < N; i++){
        if(a == A.at(i)) ans++;
        else a = A.at(i);
    }
    return ans;
}
 
template<typename T>
void chmin(T &a,T b){
    if(a>b){
        a = b;
    }
    return;
}
 
template<typename T>
void chmax(T&a,T b){
    if(a < b){
        a = b;
    }
    return;
}

/*
絶対値   abs()
配列の要素の追加   push_back() 
char→intに変換   -'0'
string→intに変換   atoi(文字列名.c_str())
配列の中身をN個の０で初期化   配列名.resize(N)
配列の中身をN個のaで初期化   配列名.assign(N,a)
配列の中からK以上の数字の最小値を出力　lower_bound(配列.begin(),配列.end(),K)
入力scanf("%lld %lld",&a,&b) みたいな感じ &を忘れずに
小数の桁数設定cout << fixed << setprecision(桁数);
*/
vector<ll> h;
vector<ll> li;
void change(ll a, ll b, ll c){
    swap(h[a],h[b]);
    swap(h[a],h[c]);
    li[h[a]] = a;
    li[h[b]] = b;
    li[h[c]] = c;
    return;
}

int main(){
    ll N; cin >> N;
    h.resize(N);
    li.resize(N);
    input_vec(h);
    ll count = 0;
    ll point = 0;
    vector<pair<ll,ll>> p;
    for(int i = 0; i < N; i++) {
        h[i]--;
        li[h[i]] = i;
    }
    for(int i = 0; i < N; i++) if(li[i] == i) point++;
    for(int i = 0; i < N; i++) if(li[i] == h[i]&&h[i]>i) p.push_back(make_pair(i,h[i]));
    for(int i = 0; point < N-2; i++){
        //cout << "point: " << point << endl;
        ll nh = li[i];
        if(nh == i)continue;
        count++;
        ll a = nh;
        ll b = i;
        ll c = -1;
        if(h[b]!=a){
            //cout << "x" << endl;
            c = h[b];
        }
        else if(b!= li[a]&&li[a] != a){
            c = li[a];
            //cout << "y" << endl;
        }
        else{
            //cout << "c: " << c << endl;
            for(int j = i+1; j < N&&c == -1; j++){
                //cout << "j: " << j <<  endl;
                if(a == j) continue;
                if(b == j) continue;
                if(li[j] == j) continue;
                if(li[j] == h[j])c = j;
            }
            if(c == -1){
                cout << -1 << endl;
                return 0;
            }
        }
        //printf("change %lld %lld %lld\n",a,b,c);
        change(a,b,c);
        if(li[i] != i) change(a,b,c);
        //output_vec(h);
        //output_vec(li);
        if(h[a] == a) point++;
        if(h[b] == b) point++;
        if(h[c] == c) point++;
        
    }
    if(point == N) cout << count << endl;
    else cout << -1 << endl;
    
    
    
    
    
    
    
    
    
    
}
accuracy: 0.84
time_ms: 30
memory_kb: 6324
final_rank: 20

code_snippet: #ifdef LOGX
#define _GLIBCXX_DEBUG
#endif
#include <bits/stdc++.h>
using namespace std;
//#include <atcoder/all>
//using namespace atcoder;

/*---------macro---------*/
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
#define rep2(i, s, n) for (int i = s; i < (int)(n); i++)
#define unless(x) if(!(x))
#define until(x) while(!(x))
#define ALL(a) a.begin(),a.end()
#define RALL(a) a.rbegin(),a.rend()
#define mybit(i,j) (((i)>>(j))&1)

/*---------type/const---------*/
const int big=1000000007;
//const int big=998244353;
const double EPS=1e-8; //適宜変える
typedef long long ll;
typedef unsigned long long ull;
typedef std::string::const_iterator state; //構文解析
const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};
const char newl='\n';
struct{
    constexpr operator int(){return -int(1e9)-10;}
    constexpr operator ll(){return -ll(1e18)-10;}
}neginf;
struct{
    constexpr operator int(){return int(1e9)+10;}
    constexpr operator ll(){return ll(1e18)+10;}
    constexpr auto operator -(){return neginf;}
}inf;

/*---------debug---------*/
#ifdef LOGX
#include <template/debug.hpp>
#else
#define dbg(...) ;
#define dbgnewl ;
#define prt(x) ;
#define _prt(x) ;
#endif

/*---------function---------*/
template<typename T> T max(const std::vector<T> &a){T ans=a[0];for(T elem:a){ans=max(ans,elem);}return ans;}
template<typename T> T min(const std::vector<T> &a){T ans=a[0];for(T elem:a){ans=min(ans,elem);}return ans;}
template<typename T,typename U> bool chmin(T &a,const U b){if(a>b){a=b;return true;}return false;}
template<typename T,typename U> bool chmax(T &a,const U b){if(a<b){a=b;return true;}return false;}
bool valid(int i,int j,int h,int w){return (i>=0 && j>=0 && i<h && j<w);}
template<class T,class U>T expm(T x,U y,const ll mod=big){T res=1;while(y){if(y&1)(res*=x)%=mod;(x*=x)%=mod;y>>=1;}return res;}
template<class T,class U>T exp(T x,U y){T res=1;while(y){if(y&1)res*=x;x*=x;y>>=1;}return res;}

struct unionfind{
    int n;
    std::vector<int> par;
    unionfind(const int _):n(_),par(_,-1){}
    int find(const int x){
        if(par[x]<0)return x;
        return par[x]=find(par[x]);
    }
    bool same(const int x,const int y){
        return find(x)==find(y);
    }
    void unite(int x,int y){
        x=find(x);
        y=find(y);
        if(x==y)return;
        if(par[x]<par[y])std::swap(x,y);
        int t=par[y]+par[x];
        par[y]=t;
        par[x]=y;
        n--;
        return;
    }
    int getsize(int i){
        i=find(i);
        return -par[i];
    }
};

int main(){
    //std::ios::sync_with_stdio(false);
    //std::cin.tie(nullptr);
    std::cout.precision(10);
/*------------------------------------*/
    
    int n;
    cin >> n;
    unionfind uf(n);
    rep(i,n){
        int h;
        cin >> h;
        h--;
        uf.unite(i,h);
    }
    int ans=0;
    bool is_odd=false;
    rep(i,n)if(uf.find(i)==i){
        int sz=uf.getsize(i);
        if(sz%2==1){
            ans+=sz/2;
        }
        else{
            ans+=(sz-2)/2;
            if(is_odd)ans+=2;
            is_odd=!is_odd;
        }
    }
    cout << (is_odd ? -1:ans) << newl;
}
accuracy: 1
time_ms: 30
memory_kb: 3836
final_rank: 7

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> P;
typedef vector<ll> vi;
typedef vector<vi> vvi;
typedef vector<P> vp;
typedef vector<bool> vb;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define REP(i,k,n) for(ll i=(ll)(k);i<(ll)(n);i++)
#define fi first
#define se second
#define pb emplace_back
#define all(a) a.begin(),a.end()
#define lb(v,k) (lower_bound(all(v),k)-v.begin())
template<class T> void out(T a){cout<<a<<'\n';}
template<class T> void outv(T v){rep(i,v.size()){if(i)cout<<' ';cout<<v[i];}cout<<'\n';}
template<class T> void outvv(T v){rep(i,v.size())outv(v[i]);}
const ll mod=998244353;
int main(){
    ll n;cin>>n;
    vi v(n);
    rep(i,n){
        cin>>v[i];v[i]--;
    }
    vb seen(n,false);
    ll ans=0,tmp=0;
    rep(i,n)if(!seen[i]){
        ll cnt=0;
        ll x=i;
        while(!seen[x]){
            seen[x]=true;
            x=v[x];cnt++;
        }
        ans+=(cnt-1)/2;
        if(cnt%2==0)tmp++;
    }
    if(tmp%2==0)out(ans+tmp);
    else out(-1);
}
accuracy: 1
time_ms: 30
memory_kb: 4696
final_rank: 10

code_snippet: #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#define _GLIBCXX_DEBUG
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using ll=long long;
using ld=long double;
ll ILL=1167167167167167167;
const int INF=2100000000;
ll mod=1e9+7;
#define rep(i,a) for (ll i=0;i<a;i++)
template<class T> using _pq = priority_queue<T, vector<T>, greater<T>>;
template<class T> ll LB(vector<T> &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> ll UB(vector<T> &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> bool chmin(T &a,const T &b){if(a>b){a=b;return 1;}else return 0;}
template<class T> bool chmax(T &a,const T &b){if(a<b){a=b;return 1;}else return 0;}
template<class T> void So(vector<T> &v) {sort(v.begin(),v.end());}
template<class T> void Sore(vector<T> &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});}
void yneos(bool a){if(a) cout<<"Yes\n"; else cout<<"No\n";}



//  rainy ~ 雨に打たれて ~
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int n;
	cin>>n;
	vector<int> p(n);
	rep(i,n){
		cin>>p[i];
		p[i]--;
	}
	vector<int> seen(n,-1);
	int ans=0,x=0;
	rep(i,n){
		if(seen[i]==1) continue;
		int tmp=0;
		int now=i;
		while(seen[now]==-1){
			seen[now]=1;
			tmp++;
			now=p[now];
		}
		if(tmp%2==0) x++;
		ans+=tmp/2;
	}
	if(x%2==1) cout<<"-1\n";
	else cout<<ans<<"\n";
}
accuracy: 1
time_ms: 10
memory_kb: 4520
final_rank: 3

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using ull = unsigned long long;
using uint = unsigned;
using pcc = pair<char, char>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pdd = pair<ld, ld>;
using tuplis = array<ll, 3>;
template<class T> using pq = priority_queue<T, vector<T>, greater<T>>;
const ll LINF=0x1fffffffffffffff;
const ll MINF=0x7fffffffffff;
const int INF=0x3fffffff;
const int MOD=1000000007;
const int MODD=998244353;
const ld DINF=numeric_limits<ld>::infinity();
const ld EPS=1e-9;
const ld PI=3.1415926535897932;
const ll dx[] = {0, 1, 0, -1, 1, -1, 1, -1};
const ll dy[] = {1, 0, -1, 0, 1, 1, -1, -1};
#define overload5(a,b,c,d,e,name,...) name
#define overload4(a,b,c,d,name,...) name
#define overload3(a,b,c,name,...) name
#define rep1(n) for(ll i=0;i<n;++i)
#define rep2(i,n) for(ll i=0;i<n;++i)
#define rep3(i,a,b) for(ll i=a;i<b;++i)
#define rep4(i,a,b,c) for(ll i=a;i<b;i+=c)
#define rep(...) overload4(__VA_ARGS__,rep4,rep3,rep2,rep1)(__VA_ARGS__)
#define rrep1(n) for(ll i=n;i--;)
#define rrep2(i,n) for(ll i=n;i--;)
#define rrep3(i,a,b) for(ll i=b;i-->(a);)
#define rrep4(i,a,b,c) for(ll i=(a)+((b)-(a)-1)/(c)*(c);i>=(a);i-=c)
#define rrep(...) overload4(__VA_ARGS__,rrep4,rrep3,rrep2,rrep1)(__VA_ARGS__)
#define each1(i,a) for(auto&&i:a)
#define each2(x,y,a) for(auto&&[x,y]:a)
#define each3(x,y,z,a) for(auto&&[x,y,z]:a)
#define each4(w,x,y,z,a) for(auto&&[w,x,y,z]:a)
#define each(...) overload5(__VA_ARGS__,each4,each3,each2,each1)(__VA_ARGS__)
#define all1(i) begin(i),end(i)
#define all2(i,a) begin(i),begin(i)+a
#define all3(i,a,b) begin(i)+a,begin(i)+b
#define all(...) overload3(__VA_ARGS__,all3,all2,all1)(__VA_ARGS__)
#define rall1(i) (i).rbegin(),(i).rend()
#define rall2(i,k) (i).rbegin(),(i).rbegin()+k
#define rall3(i,a,b) (i).rbegin()+a,(i).rbegin()+b
#define rall(...) overload3(__VA_ARGS__,rall3,rall2,rall1)(__VA_ARGS__)
#define sum(...) accumulate(all(__VA_ARGS__),0LL)
#define dsum(...) accumulate(all(__VA_ARGS__),0.0L)
#define Msum(...) accumulate(all(__VA_ARGS__),0_M)
#define elif else if
#define unless(a) if(!(a))
#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define LL(...) ll __VA_ARGS__;in(__VA_ARGS__)
#define ULL(...) ull __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) string __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define DBL(...) double __VA_ARGS__;in(__VA_ARGS__)
#define LD(...) ld __VA_ARGS__;in(__VA_ARGS__)
#define Sort(a) sort(all(a))
#define Rev(a) reverse(all(a))
#define Uniq(a) sort(all(a));a.erase(unique(all(a)),end(a))
#define vec(type,name,...) vector<type>name(__VA_ARGS__)
#define VEC(type,name,size) vector<type>name(size);in(name)
#define vv(type,name,h,...) vector<vector<type>>name(h,vector<type>(__VA_ARGS__))
#define VV(type,name,h,w) vector<vector<type>>name(h,vector<type>(w));in(name)
#define vvv(type,name,h,w,...) vector<vector<vector<type>>>name(h,vector<vector<type>>(w,vector<type>(__VA_ARGS__)))
template<class T> auto min(const T& a){ return *min_element(all(a)); }
template<class T> auto max(const T& a){ return *max_element(all(a)); }
inline ll popcnt(ull a){ return __builtin_popcountll(a); }
ll intpow(ll a, ll b){ ll ans = 1; while(b){ if(b & 1) ans *= a; a *= a; b /= 2; } return ans; }
template<class T> bool chmin(T& a, const T& b){ if(a > b){ a = b; return 1; } return 0; }
template<class T> bool chmax(T& a, const T& b){ if(a < b){ a = b; return 1; } return 0; }
template<class T, class U> bool chmin(T& a, const U& b){ if(a > T(b)){ a = b; return 1; } return 0; }
template<class T, class U> bool chmax(T& a, const U& b){ if(a < T(b)){ a = b; return 1; } return 0; }
vector<ll> iota(ll n, ll begin = 0){ vector<ll> a(n); iota(a.begin(), a.end(), begin); return a; }
vector<pll> factor(ull x){ vector<pll> ans; for(ull i = 2; i * i <= x; i++) if(x % i == 0){ ans.push_back({i, 1}); while((x /= i) % i == 0) ans.back().second++; } if(x != 1) ans.push_back({x, 1}); return ans; }
vector<ll> divisor(ull x){ vector<ll> ans; for(ull i = 1; i * i <= x; i++) if(x % i == 0) ans.push_back(i); rrep(ans.size() - (ans.back() * ans.back() == x)) ans.push_back(x / ans[i]); return ans; }
template<class T> unordered_map<T, ll> press(vector<T>& a){ Uniq(a); unordered_map<T, ll> ans; rep(a.size()) ans[a[i]] = i; return ans; }
template<class T> auto run_press(const T& a){ vector<pair<remove_const_t<remove_reference_t<decltype(a[0])>>, ll>> ans; each(x, a){ if(ans.empty() || ans.back().first != x) ans.emplace_back(x, 1); else ans.back().second++; } return ans; }
int scan(){ return getchar(); }
void scan(int& a){ scanf("%d", &a); }
void scan(unsigned& a){ scanf("%u", &a); }
void scan(long& a){ scanf("%ld", &a); }
void scan(long long& a){ scanf("%lld", &a); }
void scan(unsigned long long& a){ scanf("%llu", &a); }
void scan(char& a){ do a = getchar(); while(a == ' ' || a == '\n'); }
void scan(float& a){ scanf("%f", &a); }
void scan(double& a){ scanf("%lf", &a); }
void scan(long double& a){ scanf("%Lf", &a); }
void scan(vector<bool>& a){ for(unsigned i = 0; i < a.size(); i++){ int b; scan(b); a[i] = b; } }
void scan(char a[]){ scanf("%s", a); }
void scan(string& a){ cin >> a; }
template<class T> void scan(vector<T>&);
template<class T, size_t size> void scan(array<T, size>&);
template<class T, class L> void scan(pair<T, L>&);
template<class T, size_t size> void scan(T(&)[size]);
template<class T> void scan(vector<T>& a){ for(auto&& i : a) scan(i); }
template<class T> void scan(deque<T>& a){ for(auto&& i : a) scan(i); }
template<class T, size_t size> void scan(array<T, size>& a){ for(auto&& i : a) scan(i); }
template<class T, class L> void scan(pair<T, L>& p){ scan(p.first); scan(p.second); }
template<class T, size_t size> void scan(T (&a)[size]){ for(auto&& i : a) scan(i); }
template<class T> void scan(T& a){ cin >> a; }
void in(){}
template <class... T> void in(T&... a){ (void)initializer_list<int>{ (scan(a), 0)... }; }
void print(){ putchar(' '); }
void print(bool a){ printf("%d", a); }
void print(int a){ printf("%d", a); }
void print(unsigned a){ printf("%u", a); }
void print(long a){ printf("%ld", a); }
void print(long long a){ printf("%lld", a); }
void print(unsigned long long a){ printf("%llu", a); }
void print(char a){ printf("%c", a); }
void print(char a[]){ printf("%s", a); }
void print(const char a[]){ printf("%s", a); }
void print(float a){ printf("%.15f", a); }
void print(double a){ printf("%.15f", a); }
void print(long double a){ printf("%.15Lf", a); }
void print(const string& a){ for(auto&& i : a) print(i); }
template<class T> void print(const complex<T>& a){ if(a.real() >= 0) print('+'); print(a.real()); if(a.imag() >= 0) print('+'); print(a.imag()); print('i'); }
template<class T> void print(const vector<T>&);
template<class T, size_t size> void print(const array<T, size>&);
template<class T, class L> void print(const pair<T, L>& p);
template<class T, size_t size> void print(const T (&)[size]);
template<class T> void print(const vector<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T> void print(const deque<T>& a){ if(a.empty()) return; print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, size_t size> void print(const array<T, size>& a){ print(a[0]); for(auto i = a.begin(); ++i != a.end(); ){ putchar(' '); print(*i); } }
template<class T, class L> void print(const pair<T, L>& p){ print(p.first); putchar(' '); print(p.second); }
template<class T, size_t size> void print(const T (&a)[size]){ print(a[0]); for(auto i = a; ++i != end(a); ){ putchar(' '); print(*i); } }
template<class T> void print(const T& a){ cout << a; }
int out(){ putchar('\n'); return 0; }
template<class T> int out(const T& t){ print(t); putchar('\n'); return 0; }
template<class Head, class... Tail> int out(const Head& head, const Tail&... tail){ print(head); putchar(' '); out(tail...); return 0; }
#ifdef DEBUG
inline ll __lg(ull x){ return 63 - __builtin_clzll(x); }
#define debug(...) { print(#__VA_ARGS__); print(":"); out(__VA_ARGS__); }
#else
#define debug(...) void(0)
#endif
int first(bool i = true){ return out(i?"first":"second"); }
int First(bool i = true){ return out(i?"First":"Second"); }
int yes(bool i = true){ return out(i?"yes":"no"); }
int Yes(bool i = true){ return out(i?"Yes":"No"); }
int No(){ return out("No"); }
int YES(bool i = true){ return out(i?"YES":"NO"); }
int NO(){ return out("NO"); }
int Yay(bool i = true){ return out(i?"Yay!":":("); }
int possible(bool i = true){ return out(i?"possible":"impossible"); }
int Possible(bool i = true){ return out(i?"Possible":"Impossible"); }
int POSSIBLE(bool i = true){ return out(i?"POSSIBLE":"IMPOSSIBLE"); }
void Case(ll i){ printf("Case #%lld: ", i); }



int main(){
    LL(n);
    VEC(ll,h,n);
    ll ans=0,parity=0;
    vec(bool,used,n);
    each(i,h)i--;
    rep(n)if(!used[i]){
        ll at=i;
        ll l=0;
        do{
            l++;
            used[at]=1;
        }while(!used[at=h[at]]);
        ans+=l/2;
        parity^=l&1^1;
    }
    out(parity?-1:ans);
}
accuracy: 1
time_ms: 10
memory_kb: 4680
final_rank: 4

code_snippet: #include<bits/stdc++.h>
using namespace std;
using LL = long long;
using ULL = unsigned long long;
#define rep(i,n) for(int i=0; i<(n); i++)

int main(){
  int N; cin>>N;
  vector<int> tg;
  {
    vector<int> A(N); rep(i,N) cin>>A[i];
    vector<pair<int,int>> S(N); rep(i,N) S[i]={A[i],i};
    sort(S.begin(),S.end());
    vector<int> sw(N); rep(i,N) sw[i]=S[i].second;
    vector<bool> F(N);
    rep(s,N){
      if(F[s]) continue;
      vector<int> tmp = {s}; F[s]=true;
      int p = sw[s];
      while(p!=s){
        tmp.push_back(p); F[p]=true;
        p = sw[p];
      }
      tg.push_back(tmp.size());
    }
  }

  int ans=0, crr=0;
  for(int t : tg){
    ans += (t-1)/2;
    crr += (t-1)%2;
  }
  if(crr%2==1){ cout<<-1<<endl; }
  else cout<<(ans+crr)<<endl;
}
accuracy: 1
time_ms: 60
memory_kb: 6960
final_rank: 17

code_snippet: #include<iostream>
#include<vector>

using namespace std;

int solve(vector<int> &h){
    int con = 0, ans = 0;
    vector<bool> used(h.size());
    
    for(int i = 0; i < h.size(); i++){
        if(used[i]) continue;
        
        int size = 0, cur = i;
        
        for(;!used[cur];size++) used[cur] = true, cur = h[cur];
        
        if(size % 2 == 0) con++;
        
        ans += (size - 1) / 2;
    }
    
    if(con % 2) return -1;
    
    ans += con;
    
    return ans;
}

signed main(){
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    
    int N;
    vector<int> h;
    
    cin>>N;
    
    h.resize(N);
    
    for(int i = 0; i < N; i++){
        cin>>h[i];
        h[i]--;
    }
    
    cout<<solve(h)<<endl;
    
    return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3804
final_rank: 1

code_snippet: #include<iostream>
using namespace std;
int N;
int A[2<<17],inv[2<<17];
int ans,rev;
main()
{
	cin>>N;
	for(int i=0;i<N;i++)
	{
		cin>>A[i];
		A[i]--;
		inv[A[i]]=i;
	}
	for(int i=0;i<N;i++)if(A[i]!=i)
	{
		if(inv[i]==A[i])
		{
			A[A[i]]=A[i];
			inv[A[i]]=A[i];
			A[i]=i;
			inv[i]=i;
			rev++;
		}
		else
		{
			ans++;
			inv[A[A[i]]]=inv[i];
			inv[A[i]]=A[i];
			A[inv[i]]=A[A[i]];
			inv[i]=i;
			A[A[i]]=A[i];
			A[i]=i;
		}
	}
	cout<<(rev%2?-1:ans+rev)<<endl;
}
accuracy: 1
time_ms: 40
memory_kb: 4664
final_rank: 14