#include <bits/stdc++.h>
using namespace std;
const int mm = 2e5 + 100;
long long int d[mm], ans[mm];
bool vis[mm];
int main() {
  long long int n, m, i, j, t, a, b, c, p, k, kk;
  cin >> n;
  for (i = 1; i <= n; i++) scanf("%lld", &d[i]);
  long long int s;
  k = 0;
  for (i = 1; i <= n; i++) {
    s = 1;
    if (vis[i] == 0) {
      p = i;
      vis[i] = 1;
      while (vis[d[p]] == 0) {
        vis[d[p]] = 1;
        s++;
        p = d[p];
      }
      ans[k++] = s;
    }
  }
  sort(ans, ans + k);
  long long int sum = 0;
  if (k >= 2) {
    for (i = 0; i < k - 2; i++) {
      sum += (ans[i] * ans[i]);
    }
    a = ans[k - 1] + ans[k - 2];
    sum += (a * a);
    printf("%lld\n", sum);
  } else {
    sum += (ans[0] * ans[0]);
    printf("%lld\n", sum);
  }
}
