#include <bits/stdc++.h>
using namespace std;
int main() {
  long long n;
  cin >> n;
  vector<long long> v(n);
  for (long long i = 0; i < n; i++) {
    cin >> v[i];
    v[i]--;
  }
  long long id, tmp, ans = 0;
  vector<long long> c;
  vector<bool> vis(n);
  for (int i = 0; i < n; i++) vis[i] = false;
  for (long long i = 0; i < n; i++) {
    if (!vis[i]) {
      id = i;
      tmp = 1;
      vis[i] = true;
      while (v[i] != id) {
        tmp++;
        i = v[i];
        vis[i] = true;
      }
      c.push_back(tmp);
      ans += tmp * tmp;
      i = id;
    }
  }
  if (c.size() == 1) {
    cout << c[0] * c[0];
    return 0;
  }
  sort(c.rbegin(), c.rend());
  cout << ans + 2 * c[0] * c[1];
  return 0;
}
