#include <bits/stdc++.h>
using namespace std;
int p[100005];
bool used[100005];
int DFS(const int &nod) {
  used[nod] = true;
  if (used[p[nod]]) return 1;
  return 1 + DFS(p[nod]);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> p[i];
  vector<int> lengths;
  for (int i = 1; i <= n; ++i) {
    if (used[i]) continue;
    lengths.push_back(DFS(i));
  }
  if (lengths.size() > 1) {
    sort(lengths.begin(), lengths.end(), greater<int>());
    long long sum = (lengths[0] + lengths[1]) * 1LL * (lengths[0] + lengths[1]);
    for (int i = 2; i < lengths.size(); ++i)
      sum += lengths[i] * 1LL * lengths[i];
    cout << sum;
  } else
    cout << lengths[0] * 1LL * lengths[0];
  return 0;
}
