#include <bits/stdc++.h>   using namespace std;   const int maxn = 1e5 + 5;   long long n, num;   long long a[maxn];   long long vis[maxn];   priority_queue<long long> pq;   void fnd(long long x) {     if (vis[a[x]] == 0) {       vis[a[x]] = 1;       num++;       fnd(a[x]);     } else       return;   }   int main() {     cin >> n;     for (int i = 1; i <= n; i++) {       cin >> a[i];     }     memset(vis, 0, sizeof(vis));     for (int i = 1; i <= n; i++) {       num = 1;       if (vis[i] == 0) {         vis[i] = 1;         fnd(i);         pq.push(num);       }     }     long long t = pq.top();     pq.pop();     if (!pq.size()) {       cout << t * t << endl;     } else {       t += pq.top();       pq.pop();       long long ans = t * t;       while (pq.size()) {         t = pq.top();         pq.pop();         ans += t * t;       }       cout << ans << endl;     }     return 0;   }   