#include <bits/stdc++.h>
using namespace std;
int n, t, a;
long long sum = 0;
long long sum2 = 0;
int po[1000000];
long long g[1000000];
int p[1000000];
long long ans = 0;
int main() {
  cin >> n;
  for (int i = (1); i < (n + 1); ++i) {
    cin >> p[i];
  }
  int tmp = 0;
  int sz = 0;
  int pos;
  for (int i = (1); i < (n + 1); ++i) {
    tmp = 0;
    if (!po[i]) {
      pos = i;
      do {
        tmp++;
        po[pos] = tmp;
        pos = p[pos];
      } while (pos != i);
      g[++sz] = tmp;
    } else {
      continue;
    }
  }
  sort(g + 1, g + sz + 1);
  if (sz > 1) {
    g[sz - 1] += g[sz];
  } else {
    ans = g[1] * g[1];
  }
  for (int i = (1); i < (sz); ++i) {
    ans += g[i] * g[i];
  }
  cout << ans << endl;
  return 0;
}
