#include <bits/stdc++.h>
using namespace std;
const int N = 1048576;
bool vis[N];
int n, a[N];
vector<long long> cycle;
long long ans;
int main() {
  cin >> n;
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
  for (int i = 1; i <= n; ++i)
    if (!vis[i]) {
      int cnt = 0, j = i;
      while (!vis[j]) {
        vis[j] = true;
        cnt++;
        j = a[j];
      }
      cycle.push_back(cnt);
    }
  sort(cycle.begin(), cycle.end());
  if (cycle.size() >= 2) {
    cycle[cycle.size() - 2] += cycle[cycle.size() - 1];
    cycle.resize(cycle.size() - 1);
  }
  for (int i = 0; i < cycle.size(); ++i) ans += cycle[i] * cycle[i];
  cout << ans << endl;
  return 0;
}
