#include <bits/stdc++.h>
using namespace std;
void dfs(vector<long long int> &v, vector<long long int> &sizes) {
  long long int n = v.size() - 1;
  vector<bool> visited(n + 1, false);
  for (long long int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    long long int node = i;
    long long int size = 0;
    while (true) {
      if (visited[node]) break;
      visited[node] = true;
      node = v[node];
      size++;
    }
    sizes.push_back(size);
  }
  sort(sizes.begin(), sizes.end());
  if (sizes.size() > 1) {
    long long int k = 0;
    k += sizes.back();
    sizes.pop_back();
    k += sizes.back();
    sizes.pop_back();
    sizes.push_back(k);
  }
}
int main() {
  long long int n;
  cin >> n;
  vector<long long int> v(n + 1, -1);
  for (long long int i = 1; i <= n; i++) {
    long long int x;
    cin >> x;
    v[i] = x;
  }
  vector<long long int> sizes;
  dfs(v, sizes);
  long long int convenience = 0;
  for (long long int i = 0; i < sizes.size(); i++)
    convenience += sizes[i] * sizes[i];
  cout << convenience << endl;
}
