#include <bits/stdc++.h>
using namespace std;
const int maxn = 100000 + 10;
int n, p[maxn];
bool vis[maxn];
int main() {
  scanf("%d", &n);
  for (int i = 1; i < n + 1; i++) scanf("%d", p + i);
  int max1 = 0, max2 = 0;
  long long ans = 0;
  for (int i = 1; i < n + 1; i++)
    if (!vis[i]) {
      int len = 0;
      int x = i;
      while (!vis[x]) {
        vis[x] = true;
        x = p[x];
        len++;
      }
      if (len > max1) {
        max2 = max1;
        max1 = len;
      } else if (len > max2)
        max2 = len;
      ans += (long long)len * len;
    }
  ans -= (long long)max1 * max1;
  ans -= (long long)max2 * max2;
  long long l = max1 + max2;
  ans += l * l;
  printf("%lld\n", ans);
  return 0;
}
