#include <bits/stdc++.h>
using namespace std;
const int N = 4e5, M = 20;
long long cnt[M][1 << M], dp[1 << M];
int n, a[N], sum[N][M];
vector<int> pos[M];
inline void read_input() {
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i];
}
inline void solve() {
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < M; j++) sum[i + 1][j] = sum[i][j];
    pos[--a[i]].push_back(i);
    sum[i + 1][a[i]]++;
  }
  for (int i = 0; i < M; i++) {
    for (int j = 0; j < M; j++)
      for (auto p : pos[j]) cnt[i][1 << j] += sum[n][i] - sum[p][i];
    for (int j = 1; j < 1 << M; j++)
      cnt[i][j] = cnt[i][j & -j] + cnt[i][j ^ j & -j];
  }
  memset(dp, 63, sizeof dp);
  for (int i = dp[0] = 0; i < 1 << M; i++)
    for (int j = 0; j < M; j++)
      if (i >> j & 1)
        dp[i] = min(dp[i], dp[i ^ (1 << j)] + cnt[j][i ^ (1 << j)]);
  cout << dp[(1 << M) - 1];
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  read_input(), solve();
  return 0;
}
