#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
vector<long long> g[1000005];
vector<bool> vis(1000005, 0);
long long dx[] = {-1, 0, 1, 0};
long long dy[] = {0, -1, 0, 1};
vector<long long> v(1000005);
long long dfs(long long x) {
  vis[x] = 1;
  if (vis[v[x]] == 1)
    return 1;
  else
    return 1 + dfs(v[x]);
}
int32_t main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> v[i];
  }
  vector<long long> ans;
  for (long long i = 1; i <= n; i++) {
    if (!vis[i]) {
      long long t = dfs(i);
      ans.push_back(t);
    }
  }
  if (ans.size() == 1) {
    cout << ans[0] * ans[0] << " ";
    return 0;
  }
  sort(ans.rbegin(), ans.rend());
  long long val = 2 * ans[0] * ans[1];
  for (long long i = 0; i < ans.size(); i++) val += ans[i] * ans[i];
  cout << val;
}
