#include <bits/stdc++.h>
using namespace std;
int visited[100001] = {0};
vector<long long int> graph(100001);
vector<long long int> loops;
long long int sloops;
long long int dfs(long long int indx) {
  if (visited[indx]) return 0;
  visited[indx] = 1;
  return (dfs(graph[indx]) + 1);
}
int main(void) {
  long long int n;
  cin >> n;
  sloops = 0;
  for (long long int i = 1; i <= n; i++) {
    cin >> graph[i];
  }
  for (long long int i = 1; i <= n; i++) {
    long long int res = dfs(i);
    if (res == 1)
      sloops++;
    else if (res > 1)
      loops.push_back(res);
  }
  long long int ans = 0;
  if (loops.size() > 1) {
    sort(loops.begin(), loops.end());
    reverse(loops.begin(), loops.end());
    loops[1] += loops[0];
    for (long long int i = 1; i < loops.size(); i++) {
      ans += loops[i] * loops[i];
    }
  } else if (loops.size() == 1) {
    if (sloops) {
      sloops--;
      loops[0]++;
    }
    ans += loops[0] * loops[0];
  } else {
    if (sloops >= 2) {
      sloops -= 2;
      ans += 4;
    }
  }
  cout << (ans + sloops);
  return 0;
}
