#include <bits/stdc++.h>
using namespace std;
long long vis[100009];
std::vector<long long> v[100009];
long long size(long long s) {
  std::queue<long long> q;
  q.push(s);
  vis[s] = 1;
  long long c = 0, i;
  while (!q.empty()) {
    long long x = q.front();
    q.pop();
    c++;
    for (i = 0; i < v[x].size(); i++) {
      if (vis[v[x][i]] == 0) {
        q.push(v[x][i]);
        vis[v[x][i]] = 1;
      }
    }
  }
  return c;
}
signed main() {
  long long n, i, s = 0;
  cin >> n;
  vector<long long> v1;
  for (i = 1; i <= n; i++) {
    long long x;
    cin >> x;
    if (x == i)
      continue;
    else
      v[i].push_back(x);
  }
  for (i = 1; i <= n; i++) {
    if (vis[i] == 0) {
      long long x = size(i);
      v1.push_back(x);
    }
  }
  sort(v1.begin(), v1.end(), greater<long long>());
  if (v1.size() == 1) {
    long long x = v1[0];
    x *= x;
    cout << x;
  } else {
    long long x = v1[0], y = v1[1];
    v1.erase(v1.begin(), v1.begin() + 2);
    v1.push_back(x + y);
    for (i = 0; i < v1.size(); i++) s += pow(v1[i], 2);
    cout << s;
  }
}
