#include <bits/stdc++.h>
using namespace std;
int const N = 1 << 18;
int const M = 1 << 18;
int main(int argc, char* argv[]) {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  std::vector<int> p(1 + n);
  for (int i = 1; i <= n; ++i) cin >> p[i];
  int ux = -1, vx = -1;
  std::vector<int> visit(1 + n);
  long long ans = 0;
  for (int i = 1; i <= n; ++i) {
    if (visit[i]) continue;
    int sz = 0;
    for (int j = i; !visit[j]; j = p[j]) {
      sz++;
      visit[j] = true;
    }
    ans += sz * 1ll * sz;
    if (sz > ux) {
      vx = ux;
      ux = sz;
    } else if (sz > vx) {
      vx = sz;
    }
  }
  if (vx == -1 || ux == -1) {
  } else {
    ans -= ux * 1ll * ux;
    ans -= vx * 1ll * vx;
    ans += (ux + vx) * 1ll * (ux + vx);
  }
  cout << ans << endl;
  return 0;
}
