#include <bits/stdc++.h>
int ___read_tmp;
using namespace std;
int pp[101000];
vector<unsigned long long> sizes;
int unwind(int next) {
  int cnt = 0;
  while (pp[next] != -1) {
    int tmp = pp[next];
    pp[next] = -1;
    next = tmp;
    cnt++;
  }
  return cnt;
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = (0); i < (n); i++) {
    scanf("%d", &pp[i]);
    pp[i]--;
  }
  for (int i = (0); i < (n); i++) {
    if (pp[i] != -1) {
      sizes.push_back(unwind(i));
    }
  }
  sort(sizes.begin(), sizes.end(), std::greater<unsigned long long>());
  if (sizes.size() == 1) {
    printf("%I64d", sizes[0] * sizes[0]);
  } else {
    unsigned long long res = 0;
    unsigned long long first = sizes[0] + sizes[1];
    res = first * first;
    for (int i = (2); i < (sizes.size()); i++) {
      res += sizes[i] * sizes[i];
    }
    printf("%I64d", res);
  }
  return 0;
}
