#include <bits/stdc++.h>
using namespace std;
const long long N = 3e5 + 7;
const long long INF = 1e18;
const long long MOD = 1e9 + 7;
string s;
struct dsu {
  vector<long long> parent;
  vector<long long> size;
  long long components = 0;
  dsu(long long n = -1) {
    if (n >= 0) init(n);
  }
  void init(long long n) {
    parent.resize(n + 1);
    size.assign(n + 1, 1);
    components = n;
    for (long long i = 0; i <= n; i++) parent[i] = i;
  }
  long long get(long long x) {
    return x == parent[x] ? x : parent[x] = get(parent[x]);
  }
  bool unite(long long x, long long y) {
    x = get(x);
    y = get(y);
    if (x == y) return false;
    if (size[x] < size[y]) swap(x, y);
    parent[y] = x;
    size[x] += size[y];
    components--;
    return true;
  }
};
template <typename T, typename S>
ostream &operator<<(ostream &os, const pair<T, S> &v) {
  os << "(";
  os << v.first << "," << v.second << ")";
  return os;
}
template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
  os << "[";
  long long sz = v.size();
  for (long long i = 0; i < sz; ++i) {
    os << v[i];
    if (i != sz - 1) os << ",";
  }
  os << "]\n";
  return os;
}
template <typename T>
ostream &operator<<(ostream &os, const set<T> &v) {
  T last = *v.rbegin();
  os << "[";
  for (auto it : v) {
    os << it;
    if (it != last) os << ",";
  }
  os << "]\n";
  return os;
}
template <typename T, typename S>
ostream &operator<<(ostream &os, const map<T, S> &v) {
  for (auto it : v) {
    os << it.first << " : " << it.second << "\n";
  }
  return os;
}
template <typename Arg1>
void __f(const char *name, Arg1 &&arg1) {
  cerr << name << " : " << arg1 << '\n';
}
template <typename Arg1, typename... Args>
void __f(const char *names, Arg1 &&arg1, Args &&...args) {
  const char *comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
void solve() {
  long long n;
  cin >> n;
  vector<long long> a(n);
  dsu d(n + 2);
  for (long long i = 1, x; i <= n; i++) {
    cin >> x;
    d.unite(i, x);
  }
  vector<long long> cnt(n + 2);
  for (long long i = 1; i <= n; i++) {
    cnt[d.get(i)]++;
  }
  sort((cnt).begin(), (cnt).end());
  reverse((cnt).begin(), (cnt).end());
  long long ans = 0;
  for (long long x : cnt) ans += (x * x);
  if (cnt[0] > 0 && cnt[1] > 0)
    ans = ans - cnt[0] * cnt[0] - cnt[1] * cnt[1] +
          (cnt[1] + cnt[0]) * (cnt[1] + cnt[0]);
  cout << ans << '\n';
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t = 1;
  while (t--) {
    solve();
  }
}
