#include <bits/stdc++.h>
using namespace std;
vector<int> par;
vector<int> sz;
int find(int node) {
  while (node != par[node]) {
    node = par[node];
  }
  return node;
}
void merge(int a, int b) {
  if (a == b) return;
  if (sz[a] < sz[b]) swap(a, b);
  sz[a] += sz[b];
  par[b] = a;
}
int main() {
  int n;
  scanf("%d", &n);
  par.resize(n + 1);
  sz.resize(n + 1, 1);
  for (int i = 1; i <= n; i++) par[i] = i;
  for (int i = 1; i <= n; i++) {
    int x;
    scanf("%d", &x);
    merge(find(i), find(x));
  }
  long long sum = 0, m1 = 0, m2 = -1;
  for (int i = 1; i <= n; i++) {
    par[i] = find(i);
    if (par[i] == i) {
      sum += (long long)sz[i] * (long long)sz[i];
      m1 < sz[i] ? (m2 = m1, m1 = sz[i]) : (m2 < sz[i] ? m2 = sz[i] : m2);
    }
  }
  sum += (m1 + m2) * (m1 + m2) - m1 * m1 - m2 * m2;
  cout << sum << endl;
}
