#include <bits/stdc++.h>
using namespace std;
int arr[100001];
bool vis[100001];
int depth = 0;
void solve(int i) {
  if (vis[i]) {
    return;
  }
  vis[i] = true;
  solve(arr[i]);
  depth++;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> arr[i];
  }
  vector<int> vec;
  for (int i = 1; i <= n; i++) {
    if (vis[i]) continue;
    solve(i);
    vec.push_back(depth);
    depth = 0;
  }
  sort(vec.begin(), vec.end());
  if (vec.size() > 1) {
    vec[vec.size() - 2] += vec[vec.size() - 1];
    vec.pop_back();
  }
  long long ans = 0;
  for (long long i : vec) {
    ans += (long long)(i * i);
  }
  cout << ans;
  return 0;
}
