#include <bits/stdc++.h>
using namespace std;
int main() {
  vector<int> v;
  long long num;
  int mc[100010];
  bool fw[100010];
  long long n, x;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> mc[i];
  v.clear();
  memset(fw, false, sizeof(fw));
  for (int i = 1; i <= n; i++) {
    if (fw[i] == true) continue;
    int sz = 1;
    fw[i] = true;
    int x = mc[i];
    while (x != i) {
      fw[x] = true;
      x = mc[x];
      sz++;
    }
    v.push_back(sz);
  }
  long long ans = 0;
  sort(v.begin(), v.end());
  if (v.size() >= 2) {
    ans = v[v.size() - 1] + v[v.size() - 2];
    ans *= ans;
    for (int j = 0; j < v.size() - 2; j++) {
      ans += v[j] * v[j];
    }
  } else
    ans = n * n;
  cout << ans << endl;
}
