#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int p[maxn];
int vis[maxn];
int cnt[maxn];
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> p[i];
  }
  int x, sum;
  for (int i = 1; i <= n; i++) {
    if (vis[i]) continue;
    x = p[i];
    sum = 1;
    vis[i] = 1;
    while (!vis[x]) {
      sum++;
      vis[x] = 1;
      x = p[x];
    }
    cnt[i] = sum;
  }
  sort(cnt + 1, cnt + 1 + n);
  long long int ans = 0;
  if (n > 1)
    ans = (long long)(cnt[n] + cnt[n - 1]) * (long long)(cnt[n] + cnt[n - 1]);
  else
    ans = 1;
  for (int i = 1; i <= n - 2; i++) {
    ans += (long long)(cnt[i]) * (long long)(cnt[i]);
  }
  cout << ans << endl;
  return 0;
}
