#include <bits/stdc++.h>
using namespace std;
int destination[100100];
int color[100100];
int colorcounter[100100];
int currentcolor = 1;
vector<long long> components;
int n;
void dfs(int v) {
  color[v] = currentcolor;
  if (color[destination[v]] == color[v]) return;
  dfs(destination[v]);
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    int temp;
    scanf("%d", &temp);
    destination[i] = temp;
  }
  for (int i = 1; i <= n; i++) {
    if (color[i] == 0) {
      dfs(i);
      currentcolor++;
    }
  }
  for (int i = 1; i <= n; i++) {
    colorcounter[color[i]]++;
  }
  for (int i = 0; i <= currentcolor; i++) {
    if (colorcounter[i] == 0) continue;
    components.push_back(colorcounter[i]);
  }
  sort(components.begin(), components.end());
  if (components.size() == 1) {
    long long res = components[0] * components[0];
    printf("%lld", res);
    return 0;
  }
  long long res = 0;
  for (int i = 0; i < components.size() - 2; i++) {
    res += components[i] * components[i];
  }
  long long tmp =
      components[components.size() - 1] + components[components.size() - 2];
  res += tmp * tmp;
  printf("%lld", res);
  return 0;
}
