#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, m;
  while (cin >> n) {
    long long g[200000] = {0};
    long long a[200000] = {0}, i;
    long long sum = 0;
    for (i = 1; i <= n; i++) cin >> a[i];
    long long ans = 0;
    long long m1 = 0, m2 = 0;
    while (sum < n) {
      long long p = 0;
      for (int i = 1; i <= n; i++) {
        while (g[i] == 0) {
          g[i] = 1;
          i = a[i];
          p++;
        }
        if (p) {
          sum += p;
          ans += p * p;
          if (p >= m1) {
            m2 = m1;
            m1 = p;
          } else if (p > m2)
            m2 = p;
          break;
        }
      }
    }
    ans += 2 * m1 * m2;
    cout << ans << endl;
  }
  return 0;
}
