#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  long long n;
  cin >> n;
  vector<long long> a(n);
  for (long long i = 0; i < n; i++) cin >> a[i];
  for (long long i = 0; i < n; i++) --a[i];
  vector<bool> was(n);
  vector<long long> len;
  for (long long i = 0; i < n; i++) {
    if (!was[i]) {
      was[i] = true;
      long long cnt = 1;
      long long tmp = a[i];
      while (tmp != i) {
        was[tmp] = true;
        tmp = a[tmp];
        cnt++;
      }
      len.push_back(cnt);
    }
  }
  if (len.size() == 1) {
    cout << len[0] * len[0];
    return 0;
  }
  int max1, max2;
  if (len[0] >= len[1]) {
    max1 = 0;
    max2 = 1;
  } else {
    max1 = 1;
    max2 = 0;
  }
  for (long long i = 2; i < len.size(); i++) {
    if (len[i] > len[max1])
      max1 = i;
    else if (len[i] > len[max2])
      max2 = i;
  }
  long long sum = (len[max1] + len[max2]) * (len[max1] + len[max2]);
  for (long long i = 0; i < len.size(); i++)
    if (i != max2 && i != max1) sum += len[i] * len[i];
  cout << sum;
  return 0;
}
