#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000;
long long c, n, C[MAXN + 1], S[MAXN + 1], P[MAXN + 1];
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> P[i];
  }
  for (int i = 1; i <= n; ++i) {
    if (C[i]) {
      continue;
    }
    ++c;
    int j = i, k = i;
    do {
      C[j] = c;
      ++S[c];
      k = j;
      j = P[j];
    } while (!C[j]);
    if (C[k] != C[j]) {
      S[C[j]] += S[C[k]];
      S[C[k]] = 0;
    }
  }
  sort(S, S + MAXN + 1);
  c = 0;
  for (int i = 1; i <= MAXN - 2; ++i) {
    c += S[i] * S[i];
  }
  c += (S[MAXN - 1] + S[MAXN]) * (S[MAXN - 1] + S[MAXN]);
  cout << c << endl;
  return 0;
}
