#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e7, Base = 998244353;
const long long N = 1e5 + 7;
const long long INF = 1LL * 1000 * 1000 * 1000 * 1000 * 1000 * 1000 + 7LL;
const double pie = acos(-1.0);
const double EPS = 1e-9;
long long n, p[N], ans, x;
vector<long long> v;
long long Calco(long long idx) {
  long long x = 0, i;
  while (p[idx] != -1) i = p[idx], p[idx] = -1, idx = i, ++x;
  return x;
}
int32_t main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long i = 1; i <= n; ++i) cin >> p[i];
  for (long long i = 1; i <= n; ++i)
    if (p[i] != -1) v.push_back(Calco(i));
  sort(v.begin(), v.end());
  if (v.size() > 1) {
    x += v.back();
    v.pop_back();
    x += v.back();
    v.pop_back();
  }
  ans += (x * x);
  while (v.size()) {
    x = v.back();
    ans += x * x;
    v.pop_back();
  }
  cout << ans << '\n';
  return 0;
}
