#include <bits/stdc++.h>
using namespace std;
const long long mod = 998244353;
const int N = 1e5 + 100;
const int maxn = 1e6;
const int MAXL = sqrt(1e14) + 1;
inline int read() {
  char c = getchar();
  int x = 0, f = 1;
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
  return x * f;
}
int n, a[N];
int cnt = 0, bok[N];
long long c[N];
void dfs(int x) {
  if (bok[x]) return;
  bok[x] = 1;
  c[cnt]++;
  dfs(a[x]);
}
void solve() {
  n = read();
  for (int i = 1; i <= n; i++) {
    a[i] = read();
  }
  for (int i = 1; i <= n; i++) {
    if (bok[i] == 0) cnt++, dfs(i);
  }
  long long ans = 0;
  if (cnt == 1) {
    ans += c[1] * c[1];
  } else {
    sort(c + 1, c + cnt + 1);
    for (int i = 1; i <= cnt - 2; i++) ans += c[i] * c[i];
    long long d = c[cnt] + c[cnt - 1];
    ans += d * d;
  }
  printf("%lld\n", ans);
}
int main() {
  int T = 1;
  int tt = 0;
  while (T--) {
    solve();
  }
  return 0;
}
