#include <bits/stdc++.h>
using namespace std;
const long long N = 1e6 + 5;
const long long MOD = 1e9 + 7;
long long n, ct;
long long a[N], vis[N];
vector<long long> g[N];
void dfs(long long k) {
  if (vis[k]) return;
  vis[k] = 1;
  ct++;
  for (auto it : g[k]) dfs(it);
}
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 >> a[i];
    g[i].push_back(a[i]);
  }
  vector<long long> ans;
  for (long long i = 1; i <= n; i++) {
    if (!vis[i]) {
      ct = 0;
      dfs(i);
      ans.push_back(ct);
    }
  }
  sort(ans.rbegin(), ans.rend());
  long long answer = 0;
  long long sz = ans.size();
  for (long long i = 0; i < sz; i++) {
    answer += ans[i] * ans[i];
  }
  if (sz >= 2) {
    answer -= ans[0] * ans[0];
    answer -= ans[1] * ans[1];
    answer += (ans[0] + ans[1]) * (ans[0] + ans[1]);
  }
  cout << answer;
}
