#include <bits/stdc++.h>
using namespace std;
long long int a[1000005];
bool c[1000005];
long long int v = 0;
vector<long long int> ans;
void find(long long int i) {
  if (c[i]) return;
  c[i] = true;
  v++;
  find(a[i]);
}
int main() {
  long long int n, i, e;
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> e;
    a[i + 1] = e;
    c[i + 1] = false;
  }
  for (i = 1; i <= n; i++) {
    v = 0;
    if (c[i] == false) find(i);
    ans.push_back(v);
  }
  sort(ans.begin(), ans.end());
  n = ans.size();
  if (ans.size() == 1)
    cout << ans[0] * ans[0];
  else if (ans.size() == 2) {
    cout << (ans[0] + ans[1]) * (ans[0] + ans[1]);
  } else {
    long long int sum = 0;
    sum = (ans[n - 1] + ans[n - 2]) * (ans[n - 1] + ans[n - 2]);
    for (i = n - 3; i >= 0; i--) sum = sum + ans[i] * ans[i];
    cout << sum;
  }
}
