#include <bits/stdc++.h>
using namespace std;
long long n, na, f, j, k, i, a[100001], p[100001], ans;
bool fix[100001];
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> p[i];
  for (int i = 1; i <= n; i++)
    if (fix[i] == false) {
      j = i;
      k = 0;
      while (fix[j] == 0) {
        fix[j] = 1;
        k++;
        j = p[j];
      }
      na++;
      a[na] = k;
    }
  sort(a + 1, a + na + 1);
  if (na == 1)
    ans = n * n;
  else {
    ans = ans + (a[na] + a[na - 1]) * (a[na] + a[na - 1]);
    for (int i = 1; i < na - 1; i++) ans = a[i] * a[i] + ans;
  }
  cout << ans;
}
