#include <bits/stdc++.h>
using namespace std;
const int N = 210000;
const int MOD = 1e9 + 7;
long long int si = 0, ans = 0;
bool vis[N];
vector<long long int> adj[N];
long long int pow(long long int a, long long int b, long long int m) {
  long long int ans = 1;
  while (b) {
    if (b & 1) ans = (ans * a) % m;
    b /= 2;
    a = (a * a) % m;
  }
  return ans;
}
void dfs(long long int u) {
  if (vis[u]) return;
  si++;
  vis[u] = 1;
  for (auto &it : adj[u]) dfs(it);
}
int main() {
  long long int x, p, ans1 = 0, n, k;
  cin >> n;
  vector<long long int> v;
  for (long long int i = 0; i < n; i++) {
    cin >> x;
    adj[i + 1].push_back(x);
  }
  for (long long int i = 1; i <= n; i++) {
    if (vis[i]) {
      continue;
    }
    si = 0;
    dfs(i);
    v.push_back(si);
  }
  sort(v.begin(), v.end());
  if (v.size() >= 2) {
    p = v.size();
    p = v[p - 1] + v[p - 2];
    ans1 += p * p;
    for (long long int i = 0; i < v.size() - 2; i++) ans1 += v[i] * v[i];
    cout << ans1 << endl;
  } else {
    cout << v[0] * v[0] << endl;
  }
}
