#include <bits/stdc++.h>
using namespace std;
const int base = 1e9 + 7;
long long danhdau[100001];
long long prevv[100001];
bool cmp(long long a, long long b) { return b < a; }
void Solves() {
  long long n, t;
  cin >> n;
  long long p[n + 1];
  vector<long long> dd[n + 2];
  vector<long long> qw;
  for (int i = 1; i <= n; i++) {
    cin >> p[i];
    dd[i].push_back(p[i]);
    prevv[p[i]] = i;
  }
  for (int i = 1; i <= n; i++) {
    if (danhdau[i] > 0) continue;
    long long get = 0;
    long long dem = 0;
    long long id = i;
    while (1) {
      if (id == 0 || danhdau[id] > 0) break;
      danhdau[id]++;
      dem++;
      id = prevv[id];
    }
    queue<long long> qu;
    qu.push(i);
    while (!qu.empty()) {
      long long u = qu.front();
      qu.pop();
      danhdau[u]++;
      for (int j = 0; j < dd[u].size(); j++) {
        long long g = dd[u][j];
        if (danhdau[g] == 0) {
          qu.push(g);
          dem++;
        }
      }
    }
    qw.push_back(dem);
  }
  if (qw.size() <= 2)
    cout << n * n;
  else {
    long long ans = 0;
    sort(qw.begin(), qw.end(), cmp);
    for (int i = 0; i < 2; i++) {
      ans += qw[i];
    }
    ans *= ans;
    for (int i = 2; i < qw.size(); i++) {
      ans += qw[i] * qw[i];
    }
    cout << ans;
  }
}
int main() {
  srand(time(NULL));
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  Solves();
}
