#include <bits/stdc++.h>
using namespace std;
vector<long long> S;
long long Val[100005], n, V[100005];
long long DFS(long long x) {
  if (Val[V[x]] == 0) {
    Val[V[x]] = 1;
    return DFS(V[x]) + 1;
  } else
    return 1;
}
bool comp(long long a, long long b) { return a > b; }
int main() {
  long long i, nr = 0, sum = 0;
  cin >> n;
  for (i = 1; i <= n; i++) cin >> V[i];
  for (i = 1; i <= n; i++) {
    if (Val[i] == 0) {
      Val[i] = 1;
      nr = DFS(i);
      S.push_back(nr);
    }
  }
  sort(S.begin(), S.end(), comp);
  if (S.size() == 1) {
    cout << S[0] * S[0];
    return 0;
  } else {
    sum += (S[0] + S[1]) * (S[0] + S[1]);
    for (i = 2; i < S.size(); i++) sum += S[i] * S[i];
    cout << sum;
    return 0;
  }
  return 0;
}
