#include <bits/stdc++.h>
using namespace std;
int a[100001], n, c, b[100001];
long long ans = 0;
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> a[i];
  for (int i = 1; i <= n; ++i) {
    int k = i, l = 0;
    while (a[k] > 0) {
      int t = a[k];
      a[k] = 0;
      k = t;
      l++;
    }
    b[i] = l;
    ans += (long long)l * l;
  }
  sort(b + 1, b + 1 + n);
  ans += 2LL * b[n - 1] * b[n];
  cout << ans;
}
