#include <bits/stdc++.h>
int n, des[100001];
long long max[2];
bool vis[100001];
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%d", &des[i]);
  long long sum = 0;
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
      vis[i] = true;
      long long cnt = 1;
      int now = des[i];
      while (now != i) {
        vis[now] = true;
        cnt++;
        now = des[now];
      }
      if (cnt > max[0])
        max[1] = max[0], max[0] = cnt;
      else if (cnt > max[1])
        max[1] = cnt;
      sum += cnt * cnt;
    }
  }
  sum +=
      (max[0] + max[1]) * (max[0] + max[1]) - max[0] * max[0] - max[1] * max[1];
  printf("%lld\n", sum);
  return 0;
}
