#include <bits/stdc++.h>
const int inf = INT_MAX;
const int MAX = 1e6 + 8;
const long long MOD = 998244353;
const int TOT_PRIMES = 1e6 + 9;
const int MAX_A = 71;
const int LN = 20;
using namespace std;
vector<int> adj[MAX];
int vis[MAX];
long long c = 0;
void dfs(int u) {
  vis[u] = 1;
  c = c + 1;
  for (auto v : adj[u]) {
    if (!vis[v]) {
      dfs(v);
    }
  }
}
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int x;
    cin >> x;
    adj[i].push_back(x);
    adj[x].push_back(i);
  }
  vector<long long> res;
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
      dfs(i);
      res.push_back(c);
      c = 0;
    }
  }
  sort(res.begin(), res.end());
  long long ans = 0;
  int m = res.size();
  if (m == 1) {
    cout << res[0] * res[0];
    return 0;
  }
  ans = res[m - 1] + res[m - 2];
  ans = ans * ans;
  for (int i = 0; i < m - 2; i++) {
    ans = ans + (res[i] * res[i]);
  }
  cout << ans;
  return 0;
}
