#include <bits/stdc++.h>
using namespace std;
long long int arr[100009];
long long int scc[100009];
long long int scount = 0;
int v[1000009];
long long int dfs(long long int idx) {
  long long int tempc = 1;
  v[idx] = 1;
  while (1) {
    if (v[arr[idx]] == 0) {
      v[arr[idx]] = 1;
      tempc += dfs(arr[idx]);
    } else
      break;
  }
  return tempc;
}
int main() {
  long long int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    cin >> arr[i];
  }
  for (int i = 1; i <= n; ++i) {
    if (v[i] == 0) {
      scc[scount++] = dfs(i);
    }
  }
  sort(scc, scc + scount);
  long long int ans = 0;
  ans +=
      (scc[scount - 1] + scc[scount - 2]) * (scc[scount - 1] + scc[scount - 2]);
  for (int i = scount - 3; i >= 0; i--) ans += scc[i] * scc[i];
  cout << ans << endl;
  return 0;
}
