#include <bits/stdc++.h>
int main() {
  int numberOfStations;
  scanf("%d", &numberOfStations);
  int stations[numberOfStations];
  int i = 0;
  while (i < numberOfStations) {
    scanf("%d", &stations[i]);
    i++;
  }
  int array[numberOfStations];
  i = 0;
  int j = 0;
  int top = 0;
  long long int loops[numberOfStations];
  int k = 0;
  int l = 0;
  int max = 0;
  int secondmax = 0;
  long long int maxConvenience = 0;
  while (i < numberOfStations) {
    if (j == 0) {
      array[j] = i + 1;
      top = array[j];
      j++;
    } else {
      array[j] = stations[i];
      stations[i] = -1;
      if (top == array[j]) {
        loops[k] = j;
        if (max == 0) {
          max = loops[k];
        } else {
          if (loops[k] > max) {
            secondmax = max;
            max = loops[k];
          } else if (loops[k] > secondmax) {
            secondmax = loops[k];
          }
        }
        maxConvenience = maxConvenience + loops[k] * loops[k];
        k++;
        j = 0;
        while (stations[l] == -1) {
          l++;
        }
        i = l;
        continue;
      }
      i = array[j] - 1;
      j++;
    }
  }
  printf("%I64d\n", maxConvenience + (long long int)2 * max * secondmax);
}
