#include <bits/stdc++.h>
using namespace std;
long long t, n, i, j, k, x, y, z, l, r, mid, ans, mod = 1e9 + 7, g, m;
long long a[100005], b[100005], c[100005];
char ch;
set<long long> s;
vector<int> v[300005], u;
void dfs(int x) {
  if (b[x]) return;
  b[x] = 1;
  y++;
  dfs(a[x]);
}
int main() {
  ios::sync_with_stdio(NULL);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (i = 1; i <= n; i++) cin >> a[i];
  for (i = 1; i <= n; i++) {
    if (b[i]) continue;
    y = 0;
    dfs(i);
    u.push_back(y);
  }
  u.push_back(0);
  sort(u.begin(), u.end(), greater<long long>());
  x = u[0] + u[1];
  ans = x * x;
  for (i = 2; i < u.size(); i++) ans += u[i] * u[i];
  cout << ans;
}
