#include <bits/stdc++.h>
using namespace std;
long long dp[1 << 20ll];
long long addon[1 << 20ll][20];
long long arr[400009];
long long adder[21][21];
long long sumas[21];
int Modifiedlog2(int A) {
  int curr = 1;
  int ret = 0;
  while (curr != A) {
    curr *= 2;
    ret++;
  }
  return ret;
}
int main() {
  long long kurac = 0;
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
    kurac |= (1 << (arr[i] - 1));
    sumas[arr[i]] += i;
  }
  for (int i = n - 1; i >= 0; i--) {
    for (int col = 1; col <= 20; col++) {
      if (col == arr[i]) continue;
      adder[arr[i]][col] += adder[col][col];
    }
    adder[arr[i]][arr[i]]++;
  }
  for (int i = 1; i < (1 << 20); i++) {
    long long rez = 1000000000000000;
    long long poz = 0;
    for (int k = 0; k < 20; k++)
      if ((1 << k) & i) poz += adder[k + 1][k + 1];
    for (int k = 0; k < 20; k++)
      if ((1 << k) & i) {
        rez =
            min(rez, dp[i - (1 << k)] + sumas[k + 1] + addon[i ^ (1 << k)][k] -
                         adder[k + 1][k + 1] * (poz - adder[k + 1][k + 1]) -
                         (adder[k + 1][k + 1] * (adder[k + 1][k + 1] - 1)) / 2);
      } else {
        addon[i][k] =
            addon[i ^ (i & -i)][k] + adder[k + 1][Modifiedlog2(i & -i) + 1];
      }
    dp[i] = rez;
  }
  cout << dp[kurac];
  return 0;
}
