#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int p[maxn];
bool used[maxn];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d", p + i);
  }
  vector<long long> v;
  for (int i = 1; i <= n; i++) {
    if (!used[i]) {
      int x = i;
      long long cnt = 0;
      do {
        used[x] = true;
        x = p[x];
        cnt++;
      } while (x != i);
      v.push_back(cnt);
    }
  }
  sort(v.begin(), v.end());
  reverse(v.begin(), v.end());
  if (v.size() == 1) {
    printf("%lld\n", v[0] * v[0]);
  } else {
    long long ans = (v[0] + v[1]) * (v[0] + v[1]);
    for (int i = 2; i < v.size(); i++) {
      ans += v[i] * v[i];
    }
    printf("%lld\n", ans);
  }
  return 0;
}
