#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n;
  cin >> n;
  long long arr[n + 1];
  for (long long i = (1); i < (n + 1); i++) cin >> arr[i];
  bool vis[n + 1];
  memset(vis, 0, sizeof(vis));
  ;
  vector<long long> res;
  for (long long i = (1); i < (n + 1); i++) {
    if (!vis[i]) {
      vis[i] = true;
      long long cnt = 1;
      long long j = arr[i];
      while (vis[j] != true) {
        vis[j] = true;
        j = arr[j];
        cnt++;
      }
      res.emplace_back(cnt);
    }
  }
  sort(res.begin(), res.end());
  long long sz = res.size();
  if (sz == 1) {
    cout << n * n << endl;
  } else {
    long long ans = res[sz - 1] + res[sz - 2];
    ans *= ans;
    for (long long i = 0; i < (sz - 2); i++) {
      ans += (res[i] * res[i]);
    }
    cout << ans << endl;
  }
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  t = 1;
  while (t--) solve();
}
