#include <bits/stdc++.h>
using namespace std;
const int INF = (int)1e9;
const int mod = (int)1e9 + 7;
const int MAX = (int)1e5 + 5;
void build() { return; }
int n;
int store[MAX];
void Init() {
  scanf("%d", &n);
  for (int i = (1); i < (n + 1); ++i) scanf("%d", store + i);
  return;
}
bitset<MAX> check;
long long siz;
void dfs(int u) {
  if (check[u]) return;
  siz++;
  check[u] = 1;
  dfs(store[u]);
  return;
}
void sol() {
  vector<long long> gp;
  for (int i = (1); i < (n + 1); ++i)
    if (!check[i]) {
      siz = 0;
      dfs(i);
      gp.push_back(siz);
    }
  if ((int)gp.size() == 1)
    printf("%lld", gp[0] * gp[0]);
  else {
    sort((gp).begin(), (gp).end(), greater<long long>());
    long long ans = (gp[0] + gp[1]) * (gp[0] + gp[1]);
    for (int i = (2); i < ((int)gp.size()); ++i) ans += gp[i] * gp[i];
    printf("%lld", ans);
  }
  return;
}
int main(void) {
  Init();
  build();
  sol();
  return 0;
}
