#include <bits/stdc++.h>   using namespace std;   long long i, j, k, n, t, s, p[100009], d[100009], a[100009];   int main() {     cin >> n;     for (i = 1; i <= n; i++) cin >> p[i];     for (i = 1; i <= n; i++)       if (!d[i]) {         k = 0;         j = i;         while (d[j] == 0) {           d[j] = 1;           j = p[j];           k++;         }         d[i] = 1;         k = max(1LL, k);         a[++t] = k;       }     sort(a + 1, a + t + 1);     for (i = 1; i <= t - 2; i++) s += a[i] * 1LL * a[i];     k = a[t - 1] + a[t];     s += k * 1LL * k;     cout << s;   }   