#include <bits/stdc++.h>
using namespace std;
long long a[100010];
long long vis[100010];
long long cnt = 0;
priority_queue<long long> s;
void dfs(long long m) {
  if (vis[m] == 1)
    return;
  else {
    cnt++;
    vis[m] = 1;
    dfs(a[m]);
  }
}
int main() {
  long long n;
  while (~scanf("%lld", &n)) {
    memset(vis, 0, sizeof(vis));
    for (long long i = 1; i <= n; i++) scanf("%lld", &a[i]);
    for (long long i = 1; i <= n; i++) {
      if (vis[i] == 0) {
        cnt = 0;
        dfs(i);
        s.push(cnt);
        vis[a[i]] = 1;
      }
    }
    long long m = s.size();
    if (m > 1) {
      long long k = s.top();
      s.pop();
      long long kk = s.top();
      s.pop();
      long long sum = (k + kk) * (k + kk);
      while (!s.empty()) {
        sum += (s.top() * s.top());
        s.pop();
      }
      printf("%lld\n", sum);
    } else {
      long long k = s.top() * s.top();
      s.pop();
      printf("%lld\n", k);
    }
  }
  return 0;
}
