#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  vector<int> v(n);
  vector<int> d(n);
  for (int i = 0; i < n; i++) cin >> d[i];
  vector<int> an;
  long long s = 0;
  for (int i = 0; i < n; i++) {
    if (v[i] == 1) continue;
    v[i] = 1;
    int c = 1, ss = i;
    while (v[d[ss] - 1] != 1) {
      c++;
      v[d[ss] - 1] = 1;
      ss = d[ss] - 1;
    }
    an.push_back(c);
  }
  if (an.size() == 1) {
    s = (long long)an[0] * (long long)an[0];
    cout << s << endl;
  } else {
    vector<int>::iterator it = max_element(an.begin(), an.end());
    int ma1 = *it;
    an.erase(it);
    it = max_element(an.begin(), an.end());
    int ma2 = *it;
    an.erase(it);
    s = ((long long)(ma1 + ma2)) * ((long long)(ma1 + ma2));
    for (int i : an) s += (long long)i * (long long)i;
    cout << s << endl;
  }
  return 0;
}
