#include <bits/stdc++.h>
using namespace std;
int power(long long int x, unsigned long long y, int p) {
  long long int res = 1;
  x = x % p;
  if (x == 0) return 0;
  while (y > 0) {
    if (y & 1) res = (res * x) % p;
    y = y >> 1;
    x = (x * x) % p;
  }
  return res;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  while (t--) {
    int n;
    cin >> n;
    int a[n + 1];
    for (long long int i = 1; i < n + 1; ++i) cin >> a[i];
    int vis[n + 1];
    for (long long int i = 1; i < n + 1; ++i) vis[i] = 0;
    vector<long long int> sz;
    for (int i = 1; i <= n; i++) {
      int x = i;
      int cnt = 0;
      while (!vis[x]) {
        vis[x] = 1;
        x = a[x];
        cnt++;
      }
      sz.push_back(cnt);
    }
    sort(sz.begin(), sz.end(), greater<int>());
    if (sz.size() == 1) {
      cout << sz[0] * sz[0] << endl;
    } else {
      long long int ans = 0;
      for (int i = 2; i < sz.size(); i++) {
        ans += sz[i] * sz[i];
      }
      cout << ans + (sz[0] + sz[1]) * (sz[0] + sz[1]) << endl;
    }
  }
  return 0;
}
