#include <bits/stdc++.h>
using namespace std;
const int MAXN = (int)1e5 + 100;
int p[MAXN];
bool used[MAXN];
vector<int> sizes;
void dfs(int v) {
  int sz = 1;
  int cur = v;
  used[v] = 1;
  while (p[cur] != v) {
    cur = p[cur];
    sz++;
    used[cur] = 1;
  }
  sizes.push_back(sz);
}
int main() {
  ios_base::sync_with_stdio(0);
  int n;
  cin >> n;
  if (!n) {
    cout << 0;
    return 0;
  }
  for (int i = 0; i < n; ++i) {
    cin >> p[i];
    --p[i];
  }
  for (int v = 0; v < n; ++v)
    if (!used[v]) dfs(v);
  if (sizes.size() == 1) {
    cout << 1ll * sizes[0] * sizes[0];
    return 0;
  }
  size_t max1_pos = 0, max2_pos = 1;
  if (sizes[max1_pos] < sizes[max2_pos]) swap(max2_pos, max1_pos);
  for (size_t i = 2; i < sizes.size(); ++i)
    if (sizes[i] > sizes[max1_pos])
      max2_pos = max1_pos, max1_pos = i;
    else if (sizes[i] > sizes[max2_pos])
      max2_pos = i;
  long long res = 0;
  for (int sz : sizes) res += 1ll * sz * sz;
  res += 2ll * sizes[max1_pos] * sizes[max2_pos];
  cout << res;
  return 0;
}
