#include <bits/stdc++.h>
using namespace std;
const int maxn = 100100;
long long n, p[maxn], fa[maxn], vis[maxn], cnt, mx1, mx2, ans;
void work() {
  if (cnt >= mx1) {
    ans += mx2 * mx2;
    mx2 = mx1;
    mx1 = cnt;
  } else if (cnt >= mx2) {
    ans += mx2 * mx2;
    mx2 = cnt;
  } else
    ans += cnt * cnt;
}
int main() {
  scanf("%lld", &n);
  memset(vis, 0, sizeof vis);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &p[i]);
    fa[i] = i;
  }
  for (int i = 1; i <= n; i++) {
    long long now = i;
    if (vis[i]) continue;
    while (!vis[now]) {
      vis[now] = 1;
      fa[now] = i;
      now = p[now];
    }
  }
  sort(fa + 1, fa + n + 1);
  mx1 = mx2 = cnt = ans = 0;
  for (int i = 1; i <= n; i++) {
    if (fa[i] != fa[i - 1]) work(), cnt = 0;
    cnt++;
  }
  work();
  ans += (mx1 + mx2) * (mx1 + mx2);
  printf("%lld\n", ans);
  return 0;
}
