#include <bits/stdc++.h>
using namespace std;
long long n, a[100010], b[100010], jwb = 0;
bool v[100010];
long long dfs(long long x) {
  v[x] = true;
  if (v[a[x]]) {
    return 1;
  } else {
    return dfs(a[x]) + 1;
  }
}
int main() {
  cin >> n;
  memset(v, false, sizeof v);
  for (long long i = 1; i <= n; ++i) {
    cin >> a[i];
    b[a[i]] = i;
  }
  vector<pair<long long, long long> > l;
  for (long long i = 1; i <= n; ++i) {
    if (!v[i]) {
      l.push_back(make_pair(dfs(i), i));
    }
  }
  if (l.size() > 1) {
    sort(l.begin(), l.end());
    long long tmp = l.back().second, tmp2 = a[tmp];
    l.pop_back();
    a[tmp] = l.back().second;
    a[b[l.back().second]] = tmp2;
    for (long long i = 1; i <= n; ++i) {
      v[i] = false;
    }
    for (long long i = 1; i <= n; ++i) {
      if (!v[i]) {
        long long len = dfs(i);
        if (len == 0)
          jwb += 1;
        else {
          jwb += len * len;
        }
      }
    }
    cout << jwb << endl;
  } else {
    cout << n * n << endl;
  }
  return 0;
}
