#include <bits/stdc++.h>
using namespace std;
int n;
int a[100005];
bool b[100005];
long long int cc;
void dfs(int i) {
  b[i] = 1;
  cc++;
  if (!b[a[i]]) {
    dfs(a[i]);
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &a[i]);
  }
  vector<long long int> c;
  for (int i = 1; i <= n; ++i) {
    if (!b[i]) {
      cc = 0;
      dfs(i);
      c.push_back(cc);
    }
  }
  sort(c.begin(), c.end());
  if ((int)c.size() == 1) {
    printf("%lld\n", c[0] * c[0]);
    return 0;
  }
  long long int ans = 0;
  for (int i = 0; i < (int)c.size(); ++i) {
    if (i < (int)c.size() - 2) {
      ans += (c[i] * c[i]);
    } else {
      ans += ((c[i] + c[i + 1]) * (c[i] + c[i + 1]));
      break;
    }
  }
  printf("%lld\n", ans);
}
