#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 7;
long long to[maxn];
long long n;
bool vis[maxn];
vector<long long> lens;
void fuck(long long n, long long cur) {
  if (vis[n]) {
    lens.push_back(cur);
    return;
  }
  vis[n] = 1;
  fuck(to[n], cur + 1);
  return;
}
int main() {
  cin >> n;
  memset(vis, 0, sizeof vis);
  for (int i = 1; i <= n; ++i) {
    cin >> to[i];
  }
  for (int i = 1; i <= n; ++i) {
    if (!vis[i]) {
      fuck(i, 0);
    }
  }
  if (lens.size() == 1) {
    cout << n * n << endl;
    return 0;
  }
  sort(lens.begin(), lens.end(), [=](int a, int b) { return a > b; });
  long long size = lens.size();
  long long sum1 = lens[0] + lens[1];
  long long ans = sum1 * sum1;
  for (int i = 2; i < size; ++i) {
    ans += lens[i] * lens[i];
  }
  cout << ans << endl;
}
