#include <bits/stdc++.h>
using namespace std;
long long int ans = 0;
long long int gcd(long long int a, long long int b) {
  if (b == 0) return a;
  ans += a / b;
  return gcd(b, a % b);
}
long long int mod = 1000000009;
long long int binpower(long long int a, long long int b) {
  long long int ans = 1;
  while (b > 0) {
    if (b & 1) ans = (ans * a) % mod;
    a = (a * a) % mod;
    b >>= 1;
  }
  return ans;
}
const long long int N = 100005;
vector<long long int> thisone;
vector<long long int> arr;
bool visited[N];
long long int n;
void dfs(int node) {
  visited[node] = true;
  thisone.push_back(node);
  if (!visited[arr[node] - 1]) dfs(arr[node] - 1);
}
int main() {
  int test = 1;
  while (test--) {
    cin >> n;
    long long int val;
    for (int i = 0; i < n; ++i) {
      cin >> val;
      arr.push_back(val);
    }
    for (int i = 0; i < n; ++i) visited[i] = false;
    vector<long long int> leng;
    for (int i = 0; i < n; ++i) {
      if (!visited[i]) {
        thisone.clear();
        dfs(i);
        leng.push_back(thisone.size());
      }
    }
    sort(leng.begin(), leng.end(), greater<long long int>());
    if (leng.size() == 1) {
      cout << (leng[0] * leng[0]);
      exit(0);
    }
    long long int ans = 0;
    ans += ((leng[0] + leng[1]) * (leng[0] + leng[1]));
    for (int i = 2; i < leng.size(); ++i) ans += (leng[i] * leng[i]);
    cout << ans;
  }
}
