#include <bits/stdc++.h>
using namespace std;
const int maxn = 10e6 + 4;
bool vis[100005];
long long co, to[100005];
vector<long long> v;
void dfs(long long v) {
  if (vis[v]) return;
  co++;
  vis[v] = true;
  dfs(to[v]);
}
int main() {
  long long n;
  scanf("%lld", &n);
  for (long long k = 1; k < n + 1; k++) scanf("%lld", &to[k]);
  for (long long k = 1; k < n + 1; k++)
    if (!vis[k]) {
      co = 0;
      dfs(k);
      v.push_back(co);
    }
  sort(v.begin(), v.end());
  if (v.size() >= 2) {
    v[v.size() - 2] += v[v.size() - 1];
    v.resize(v.size() - 1);
  }
  long long ans = 0;
  for (long long k = 0; k < v.size(); k++) ans += (v[k]) * v[k];
  cout << ans;
  return 0;
}
