#include <bits/stdc++.h>
using namespace std;
int n;
int p[100000];
int c[100000];
int main() {
  ios_base::sync_with_stdio(0);
  cin >> n;
  for (int i = 0; i < n; ++i) {
    cin >> p[i];
    --p[i];
  }
  vector<long long int> loops;
  for (int i = 0; i < n; ++i) {
    if (c[i]) continue;
    int j = i;
    int q = 0;
    while (c[j] == 0) {
      c[j] = 1;
      j = p[j];
      ++q;
    }
    loops.push_back(q);
  }
  sort(loops.begin(), loops.end());
  if (loops.size() > 1) {
    loops[loops.size() - 2] += loops[loops.size() - 1];
    loops.pop_back();
  }
  long long int ans = 0;
  for (int i = 0; i < loops.size(); ++i) {
    ans += loops[i] * loops[i];
  }
  cout << ans << endl;
  return 0;
}
