#include <bits/stdc++.h>
using namespace std;
#define sz size()
#define x first
#define y second
#define mp make_pair
#define mpp(a,b,c) make_pair(make_pair(a,b),c)
#define pb push_back
#define all(v) v.begin(),v.end()
#define EPS 1e-9
#define MOD 1000000007
#define MAX 100005
typedef pair<int,int> pii;
typedef long long ll;

int a[MAX];
vector<int> v;
bool vis[MAX];

int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        scanf("%d",a + i);

    for(int i=1; i<=n; i++)
        if(!vis[i])
    {
        int p = i;
        int c = 0;
        while(!vis[p])
        {
            vis[p] = 1;
            c++;
            p = a[p];
        }
        v.pb(c);
    }

    ll ans = 0;

    sort(all(v));

    ans += v[v.sz - 1];
    if(v.sz >= 2)
        ans += v[v.sz - 2];

    /*for(int i = v.sz - 1; i >= max((int)v.sz - 2,0); i--)
        ans += v[i];*/

    ans *= ans;

    if(v.sz > 2)
    for(int i=0; i<(int)v.sz - 2; i++)
        ans += v[i] *1LL* v[i];

    cout << ans << endl;

}


#include <bits/stdc++.h>
using namespace std;
#define sz size()
#define x first
#define y second
#define mp make_pair
#define mpp(a,b,c) make_pair(make_pair(a,b),c)
#define pb push_back
#define all(v) v.begin(),v.end()
#define EPS 1e-9
#define MOD 1000000007
#define MAX 100005
typedef pair<int,int> pii;
typedef long long ll;

int a[MAX];
vector<int> v;
bool vis[MAX];

int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        scanf("%d",a + i);

    for(int i=1; i<=n; i++)
        if(!vis[i])
    {
        int p = i;
        int c = 0;
        while(!vis[p])
        {
            vis[p] = 1;
            c++;
            p = a[p];
        }
        v.pb(c);
    }

    ll ans = 0;

    sort(all(v));

    for(int i = v.sz - 1; i >= max((int)v.sz - 2,0); i--)
        ans += v[i];

    ans *= ans;

    for(int i=0; i<(int)v.sz - 2; i++)
        ans += v[i];

    cout << ans << endl;

}


#include <bits/stdc++.h>
using namespace std;

void showpq(priority_queue <int> gq)
{
    priority_queue <int> g = gq;
    while (!g.empty())
    {
        cout << '\t' << g.top();
        g.pop();
    }
    cout << '\n';
}

int main(){
    int n;  cin >> n;
    vector<int> v(n+1, 0);

    priority_queue <int> cycleSize;

    for(int i=1; i<=n; i++){
        int temp;    cin >> temp;
        v[i] = temp;
    }

    for(int i=1; i<=n; i++){
        if(v[i]==-1){
            continue;
        }

        int t = v[i];
        int c = 0;
        v[i] = -1;
        while(t!=-1){
            int x = t;
            t = v[t];

            v[x] = -1;
            c++;
        }

        cycleSize.push(c);
    }

    int ans = 0;

    if(cycleSize.size() >= 2){
        int largest = cycleSize.top();  cycleSize.pop();
        int secondLargest = cycleSize.top();    cycleSize.pop();
        ans+= (largest + secondLargest) * (largest + secondLargest);

        while(cycleSize.size() > 0){
            int s = cycleSize.top();    cycleSize.pop();
            ans+= s*s;
        }
    }

    cout << ans << endl;

}


#include <bits/stdc++.h>
using namespace std;

void showpq(priority_queue <int> gq)
{
    priority_queue <int> g = gq;
    while (!g.empty())
    {
        cout << '\t' << g.top();
        g.pop();
    }
    cout << '\n';
}

long int main(){
    long long n;  cin >> n;
    vector<long long> v(n+1, 0);

    priority_queue <long long> cycleSize;

    for(long long i=1; i<=n; i++){
        long long temp;    cin >> temp;
        v[i] = temp;
    }

    for(long long i=1; i<=n; i++){
        if(v[i]==-1){
            continue;
        }

        long long t = v[i];
        long long c = 0;
        v[i] = -1;
        while(t!=-1){
            long long x = t;
            t = v[t];

            v[x] = -1;
            c++;
        }

        cycleSize.push(c);
    }

    unsigned long long ans = 0;

    if(cycleSize.size() >= 2){
        unsigned long long largest = cycleSize.top();  cycleSize.pop();
        unsigned long long secondLargest = cycleSize.top();    cycleSize.pop();
        ans+= (largest + secondLargest) * (largest + secondLargest);

        while(cycleSize.size() > 0){
            unsigned long long s = cycleSize.top();    cycleSize.pop();
            ans+= s*s;
        }
    }else{
        unsigned long long s = cycleSize.top();    cycleSize.pop();
        ans+= s*s;
    }

    cout << ans << endl;

}


#include <bits/stdc++.h>
using namespace std;

void showpq(priority_queue <int> gq)
{
    priority_queue <int> g = gq;
    while (!g.empty())
    {
        cout << '\t' << g.top();
        g.pop();
    }
    cout << '\n';
}

int main(){
    int n;  cin >> n;
    vector<int> v(n+1, 0);

    priority_queue <int> cycleSize;

    for(int i=1; i<=n; i++){
        int temp;    cin >> temp;
        v[i] = temp;
    }

    for(int i=1; i<=n; i++){
        if(v[i]==-1){
            continue;
        }

        int t = v[i];
        int c = 0;
        v[i] = -1;
        while(t!=-1){
            int x = t;
            t = v[t];

            v[x] = -1;
            c++;
        }

        cycleSize.push(c);
    }

    int ans = 0;

    if(cycleSize.size() >= 2){
        int largest = cycleSize.top();  cycleSize.pop();
        int secondLargest = cycleSize.top();    cycleSize.pop();
        ans+= (largest + secondLargest) * (largest + secondLargest);

        while(cycleSize.size() > 0){
            int s = cycleSize.top();    cycleSize.pop();
            ans+= s*s;
        }
    }else{
        int s = cycleSize.top();    cycleSize.pop();
        ans+= s*s;
    }

    cout << ans << endl;

}


#include <bits/stdc++.h>
using namespace std;

void showpq(priority_queue <int> gq)
{
    priority_queue <int> g = gq;
    while (!g.empty())
    {
        cout << '\t' << g.top();
        g.pop();
    }
    cout << '\n';
}

int main(){
    long long n;  cin >> n;
    vector<long long> v(n+1, 0);

    priority_queue <long long> cycleSize;

    for(long long i=1; i<=n; i++){
        long long temp;    cin >> temp;
        v[i] = temp;
    }

    for(long long i=1; i<=n; i++){
        if(v[i]==-1){
            continue;
        }

        long long t = v[i];
        long long c = 0;
        v[i] = -1;
        while(t!=-1){
            long long x = t;
            t = v[t];

            v[x] = -1;
            c++;
        }

        cycleSize.push(c);
    }

    unsigned long long ans = 0;

    if(cycleSize.size() >= 2){
        unsigned long long largest = cycleSize.top();  cycleSize.pop();
        unsigned long long secondLargest = cycleSize.top();    cycleSize.pop();
        ans+= (largest + secondLargest) * (largest + secondLargest);

        while(cycleSize.size() > 0){
            unsigned long long s = cycleSize.top();    cycleSize.pop();
            ans+= s*s;
        }
    }else{
        unsigned long long s = cycleSize.top();    cycleSize.pop();
        ans+= s*s;
    }

    cout << ans << endl;

}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
ll flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    ll t;cin>>t;
    ll arr[t+1];
    fo(i,1,t+1)cin>>arr[i];
    vector<vector<ll> > v;
    vector<ll>ans;
    v.resize(t+1);
    ans.resize(t+1);
    fo(i,1,t+1){
        int j=i;
        do{
            v[i].push_back(j);
            j=arr[j];
        }while(i!=j);
    }
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        ll co=0;
        fo(j,0,v[i].size()){
            co++;
            flag[v[i][j]]=1;
        }
        ans[i]=(co);
    }
    sort(ans.begin(),ans.end());
    ll co=(ans[t]+ans[t-1])*(ans[t]+ans[t-1]);
    for(int i=t-2;i>=0;i--){
        co+=ans[i];
    }
    cout<<co<<endl;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
ll flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    ll t;cin>>t;
    ll arr[t+1];
    fo(i,1,t+1)cin>>arr[i];
    vector<vector<ll> > v;
    vector<ll>ans;
    v.resize(t+1);
    fo(i,1,t+1){
        int j=i;
        do{
            v[i].push_back(j);
            j=arr[j];
        }while(i!=j);
    }
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        ll co=0;
        fo(j,0,v[i].size()){
            co++;
            flag[v[i][j]]=1;
        }
        ans[i]=(co);
    }
    sort(ans.begin(),ans.end());
    ll co=(ans[t]+ans[t-1])*(ans[t]+ans[t-1]);
    for(int i=t-2;i>=0;i--){
        co+=ans[i];
    }
    cout<<co<<endl;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
ll flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    ll t;cin>>t;
    ll arr[t+1],co;
    fo(i,1,t+1)cin>>arr[i];
    vector<ll>ans;
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        ll j=i;
        co=0;
        do{
            if(flag[j]==1)break;
            co++;
            flag[j]=1;
            j=arr[j];
        }while(true);
        ans.push_back(co);
    }
    ///

    ll a=0,b=0,c=0,d=0;
    fo(i,0,ans.size()){
        if(ans[i]>a){
            a=ans[i];
            b=i;
        }
    }
    ans[b]=0;
    fo(i,0,ans.size()){
        if(ans[i]>c){
            c=ans[i];
            d=i;
        }
    }
    ans[d]=0;
    co=(a+c)*(a+c);
    for(int i=0;i<ans.size();i++){
        co+=(ans[i])*(ans[i]);
    }
    cout<<co<<endl;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
ll flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    ll t;cin>>t;
    ll arr[t+1],co;
    fo(i,1,t+1)cin>>arr[i];
    vector<ll>ans;
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        ll j=i;
        co=0;
        do{
            if(flag[j]==1)break;
            co++;
            flag[j]=1;
            j=arr[j];
        }while(true);
        ans.push_back(co);
    }
    ///

    ll a=0,b=0,c=0,d=0;
    fo(i,0,ans.size()){
        if(ans[i]>a){
            a=ans[i];
            b=i;
        }
    }
    ans[b]=0;
    fo(i,0,ans.size()){
        if(ans[i]>c){
            c=ans[i];
            d=i;
        }
    }
    ans[d]=0;
    ull co1=0;
    co1=(a+c)*(a+c);
    for(int i=0;i<ans.size();i++){
        co1+=ans[i];
    }
    cout<<co1<<endl;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
int flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    int t;cin>>t;
    int arr[t+1];
    fo(i,1,t+1)cin>>arr[i];
    vector<vector<int> > v;
    vector<int>ans;
    v.resize(t+1);
    ans.resize(t+1);
    fo(i,1,t+1){
        int j=i;
        do{
            v[i].push_back(j);
            j=arr[j];
        }while(i!=j);
    }
    int flag[t+1]={};
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        int co=0;
        fo(j,0,v[i].size()){
            co++;
            flag[v[i][j]]=1;
        }
        ans[i]=(co);
    }
    sort(ans.begin(),ans.end());
    int co=(ans[t]+ans[t-1])*(ans[t]+ans[t-1]);
    for(int i=t-2;i>=0;i--){
        co+=ans[i];
    }
    cout<<co;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
ll flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    ll t;cin>>t;
    ll arr[t+1];
    fo(i,1,t+1)cin>>arr[i];
    vector<vector<ll> > v;
    vector<ll>ans;
    v.resize(t+1);
    fo(i,1,t+1){
        int j=i;
        do{
            v[i].push_back(j);
            j=arr[j];
        }while(i!=j);
    }
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        ll co=0;
        fo(j,0,v[i].size()){
            co++;
            flag[v[i][j]]=1;
        }
        ans.push_back(co);
    }
    sort(ans.begin(),ans.end());
    ll co=(ans[t]+ans[t-1])*(ans[t]+ans[t-1]);
    for(int i=t-2;i>=0;i--){
        co+=ans[i];
    }
    cout<<co<<endl;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
ll flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    ll t;cin>>t;
    ll arr[t+1];
    fo(i,1,t+1)cin>>arr[i];
    vector<vector<ll> > v;
    vector<ll>ans;
    v.resize(t+1);
    ans.resize(t+1);
    fo(i,1,t+1){
        int j=i;
        do{
            v[i].push_back(j);
            j=arr[j];
        }while(i!=j);
    }
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        ll co=0;
        fo(j,0,v[i].size()){
            co++;
            flag[v[i][j]]=1;
        }
        ans[i]=(co);
    }
    ll a=0,b=0,c=0,d=0;
    fo(i,0,ans.size()){
        if(ans[i]>a){
            a=ans[i];
            b=i;
        }
    }
    ans[b]=0;
    fo(i,0,ans.size()){
        if(ans[i]>c){
            c=ans[i];
            d=i;
        }
    }
    ans[d]=0;

    ll co=(a+c)*(a+c);
    for(int i=0;i<ans.size();i++){
        co+=ans[i];
    }
    cout<<co<<endl;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


/*
Accepted for God sake
  /\___/\
 ( =^.^= )
  (") (")_/
*/
#include <bits/stdc++.h>
using namespace std;
#define Ahmed_El_Moataz           ios_base::sync_with_stdio(0);cin.tie(0);
#define fo(i,a,b)                 for(int i=(a);i<(b);i++)
#define dfo(i,a,b)                  for(int i=(a-1);i>=b;i--)
#define CN(arr,t)                 for(int i=0;i<t;i++)cin>>arr[i]
typedef long long  ll;typedef unsigned long long  ull;
const ll mod = 1000000007  ,mod2 = 2e9 ;double Pi=3.141592653589793238;
/* a=97  A=65 z=122 Z=90 0=48 setw() <<setprecision(9) I64d ull::18446744073709551615*/
ull gcd(ull a,ull b){return b==0 ? a:gcd(b,a%b);}
ll lcm(ll a,ll b){return (a*b)/gcd(a,b);}
ull FP(ull b,ull p){if(p==0)return 1;return (p%2==1)? (b)*FP(b*b,p/2):FP(b*b,p/2);}
/********************************************************************/
ll flag[100001]={};
int main()
{
    Ahmed_El_Moataz
    ll t;cin>>t;
    ll arr[t+1],co;
    fo(i,1,t+1)cin>>arr[i];
    vector<ll>ans;
    fo(i,1,t+1){
        if(flag[i]==1)continue;
        ll j=i;
        co=0;
        do{
            if(flag[j]==1)break;
            co++;
            flag[j]=1;
            j=arr[j];
        }while(true);
        ans.push_back(co);
    }
    ///

    ll a=0,b=0,c=0,d=0;
    fo(i,0,ans.size()){
        if(ans[i]>a){
            a=ans[i];
            b=i;
        }
    }
    ans[b]=0;
    fo(i,0,ans.size()){
        if(ans[i]>c){
            c=ans[i];
            d=i;
        }
    }
    ans[d]=0;
    co=(a+c)*(a+c);
    for(int i=0;i<ans.size();i++){
        co+=ans[i];
    }
    cout<<co<<endl;
/*
    fo(i,1,t+1){
        cout<<ans[i]<<" ";
    }
    cout<<endl;
    fo(i,1,t+1){
        fo(j,0,v[i].size()){
            cout<<v[i][j]<<" ";
        }
        cout<<"\n";
    }
*/
}


#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 100010;
int fa[N], cnt[N];
bool vis[N];
int main() {
	int n;
	cin >> n;
	for(int i = 1; i <= n; i ++) cin >> fa[i];
	for(int i = 1; i <= n; i ++) {
		if(!vis[i]) {
			ll ans = vis[i] = 1, tmp = fa[i];
			while(!vis[tmp]) {
				ans ++;
				vis[tmp] = true;
				tmp = fa[tmp];
			}
			cnt[i] = ans;
		}
	}
	sort(cnt+1, cnt+1+n);
	ll sum = 0;
	if(n > 1) sum = (ll)(cnt[n]+cnt[n-1])*(ll)(cnt[n]+cnt[n-1]);
	else sum = 1;
	for(int i = 1; i <= n-2; i ++) {
		sum += (ll)cnt[i]*(ll)cnt[i];
	}
	printf("%lld\n",sum);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int fa[N];
bool vis[N];
vector<int> vs;
int main() {
	int n;
	cin >> n;
	for(int i = 1; i <= n; i ++) cin >> fa[i];
	for(int i = 1; i <= n; i ++) {
		if(!vis[i]) {
			int ans = 0, tmp = i;
			while(!vis[tmp]) {
				ans ++;
				vis[tmp] = true;
				tmp = fa[tmp];
			}
			vs.push_back(ans);
		}
	}
	int len = vs.size();
	//printf("%d==\n",len);
	if(len <= 2) return 0*printf("%d\n",n*n);
	sort(vs.begin(), vs.end());
	//for(int i = 0; i < len; i ++) printf("%d==-=-\n",vs[i]);
	int sum = (vs[len-1]+vs[len-2])*(vs[len-1]+vs[len-2]);
	for(int i = 0; i < len-2; i ++) sum += vs[i]*vs[i];
	printf("%d\n",sum);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int fa[N], a[N], ans = 0;
vector<int> vs;
map<int, int> mp;
int find(int x) {
	return fa[x] = (fa[x] == x ? x: find(fa[x]));
}
void uni(int x, int y) {
	if(x < y) fa[y] = x;
	else fa[x] = y;
}
int main() {
	int n, x;
	cin >> n;
	for(int i = 1; i <= n; i ++) fa[i] = i;
	for(int i = 1; i <= n; i ++) {
		cin >> x;
		uni(i, x);
	}
	for(int i = 1; i <= n; i ++) {
		if(find(i) == i) {
			ans ++;
			vs.push_back(i);
		}
	}
	for(int i = 1; i <= n; i ++) {
		mp[find(i)] ++;
	}
	if(ans <= 2) return 0*printf("%d\n",n*n);
	for(int i = 0; i < n; i ++) {
		a[i] = mp[vs[i]];
	}
	sort(a, a+n);
	int sum = (a[n-1]+a[n-2])*(a[n-1]+a[n-2]);
	for(int i = 0; i < n-2; i ++) sum += a[i]*a[i];
	printf("%d\n",sum);
	return 0;
}


#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 100010;
int fa[N];
bool vis[N];
vector<int> vs;
int main() {
	int n;
	cin >> n;
	for(int i = 1; i <= n; i ++) cin >> fa[i];
	for(int i = 1; i <= n; i ++) {
		if(!vis[i]) {
			int ans = 0, tmp = i;
			while(!vis[tmp]) {
				ans ++;
				vis[tmp] = true;
				tmp = fa[tmp];
			}
			vs.push_back(ans);
		}
	}
	int len = vs.size();
	//printf("%d==\n",len);
	if(len <= 2) return 0*printf("%lld\n",1LL*n*n);
	sort(vs.begin(), vs.end());
	//for(int i = 0; i < len; i ++) printf("%d==-=-\n",vs[i]);
	ll sum = 1LL*(vs[len-1]+vs[len-2])*(vs[len-1]+vs[len-2]);
	for(int i = 0; i < len-2; i ++) sum += 1LL*vs[i]*vs[i];
	printf("%d\n",sum);
	return 0;
}


#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 100010;
int fa[N];
bool vis[N];
vector<ll> vs;
int main() {
	int n;
	cin >> n;
	for(int i = 1; i <= n; i ++) cin >> fa[i];
	for(int i = 1; i <= n; i ++) {
		if(!vis[i]) {
			ll ans = vis[i] = 1, tmp = fa[i];
			while(!vis[tmp]) {
				ans ++;
				vis[tmp] = true;
				tmp = fa[tmp];
			}
			vs.push_back(ans);
		}
	}
	int len = vs.size();
	//printf("%d==\n",len);
	if(len <= 2) return 0*printf("%lld\n",1LL*n*n);
	sort(vs.begin(), vs.end());
	//for(int i = 0; i < len; i ++) printf("%d==-=-\n",vs[i]);
	ll sum = 1LL*(vs[len-1]+vs[len-2])*(vs[len-1]+vs[len-2]);
	for(int i = 0; i < len-2; i ++) sum += 1LL*vs[i]*vs[i];
	printf("%d\n",sum);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int fa[N], a[N], ans = 0;
int find(int x) {
	return fa[x] = (fa[x] == x ? x: find(fa[x]));
}
void uni(int x, int y) {
	if(x < y) fa[y] = x;
	else fa[x] = y;
}
int main() {
	int n, x;
	cin >> n;
	for(int i = 1; i <= n; i ++) fa[i] = i;
	for(int i = 1; i <= n; i ++) {
		cin >> x;
		uni(i, x);
	}
	for(int i = 1; i <= n; i ++) {
		a[find(i)]++;
		if(find(i) == i) {
			ans ++;

		}
	}
	if(ans <= 2) return 0*printf("%d\n",n*n);
	sort(a+1, a+1+n);
	int sum = (a[n-1]+a[n])*(a[n-1]+a[n]);
	for(int i = 1; i <= n-2; i ++) sum += a[i]*a[i];
	printf("%d\n",sum);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n, p[100000 + 100];
int rs[100000 + 100];
int dfs(int u){
	if(p[u] == -1) return 0;
	int v = p[u];
	p[u] = -1;
	return 1 + dfs(v);
}
int main(void){
	cin >> n;
	memset(p, -1, sizeof(p));
	memset(rs, 0, sizeof(rs));
	int k = 0;
	for(int i = 1; i <= n; i++){
		cin >> p[i];
	}
	for(int i = 1; i <= n; i++){
		if(p[i] != -1){
			rs[k] = dfs(p[i]);
			k++;
		}
	}
	cout << k << endl;
	sort(rs, rs + k);
	//for(int i = 0; i < k; i++) cout << rs[i] << endl;
	int tmp = rs[k - 1] + rs[k - 2];
	int ans = tmp * tmp;
	for(int i = 0; i <= k - 3; i++){
		ans += rs[i];
	}
	cout << ans << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n, p[100000 + 100];
int rs[100000 + 100];
int dfs(int u){
	if(p[u] == -1) return 0;
	int v = p[u];
	p[u] = -1;
	return 1 + dfs(v);
}
int main(void){
	cin >> n;
	memset(p, -1, sizeof(p));
	memset(rs, 0, sizeof(rs));
	int k = 0;
	for(int i = 1; i <= n; i++){
		cin >> p[i];
	}
	for(int i = 1; i <= n; i++){
		if(p[i] != -1){
			rs[k] = dfs(p[i]);
			k++;
		}
	};
	sort(rs, rs + k);
	int tmp = rs[k - 1] + rs[k - 2];
	int ans = tmp * tmp;
	for(int i = 0; i <= k - 3; i++){
		ans += rs[i];
	}
	cout << ans << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n, p[100000 + 100];
int dfs(int u){
	if(p[u] == -1) return 0;
	int v = p[u];
	p[u] = -1;
	return 1 + dfs(v);
}
int main(void){
	cin >> n;
	memset(p, -1, sizeof(p));
	memset(rs, 0, sizeof(rs));
	int k = 0;
	for(int i = 1; i <= n; i++){
		cin >> p[i];
	}
	for(int i = 1; i <= n; i++){
		if(p[i] != -1){
			rs[k] = dfs(p[i]);
			k++;
		}
	};
	sort(rs, rs + k);
	int tmp = rs[k - 1] + rs[k - 2];
	int ans = tmp * tmp;
	for(int i = 0; i <= k - 3; i++){
		ans += rs[i] * rs[i];
	}
	cout << ans << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n, p[100000 + 100];
int rs[100000 + 100];
int dfs(int u){
	if(p[u] == -1) return 0;
	int v = p[u];
	p[u] = -1;
	return 1 + dfs(v);
}
int main(void){
	cin >> n;
	memset(p, -1, sizeof(p));
	memset(rs, 0, sizeof(rs));
	int k = 0;
	for(int i = 1; i <= n; i++){
		cin >> p[i];
	}
	for(int i = 1; i <= n; i++){
		if(p[i] != -1){
			rs[k] = dfs(p[i]);
			k++;
		}
	};
	sort(rs, rs + k);
	int tmp = rs[k - 1] + rs[k - 2];
	int ans = tmp * tmp;
	for(int i = 0; i <= k - 3; i++){
		ans += rs[i] * rs[i];
	}
	cout << ans << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int n, p[100000 + 100];
int rs[100000 + 100];
int dfs(int u){
	if(p[u] == -1) return 0;
	int v = p[u];
	p[u] = -1;
	return 1 + dfs(v);
}
int main(void){
	cin >> n;
	memset(p, -1, sizeof(p));
	memset(rs, 0, sizeof(rs));
	int k = 0;
	for(int i = 1; i <= n; i++){
		cin >> p[i];
	}
	for(int i = 1; i <= n; i++){
		if(p[i] != -1){
			rs[k] = dfs(p[i]);
			k++;
		}
	};
	sort(rs, rs + k);
	ll tmp = rs[k - 1] + rs[k - 2];
	ll ans = tmp * tmp;
	for(int i = 0; i <= k - 3; i++){
		ans += rs[i] * rs[i];
	}
	cout << ans << endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n, p[100000 + 100];
int rs[100000 + 100];
int dfs(int u){
	if(p[u] == -1) return 0;
	int v = p[u];
	p[u] = -1;
	return 1 + dfs(v);
}
int main(void){
	cin >> n;
	int k = 0;
	for(int i = 1; i <= n; i++){
		cin >> p[i];
	}
	for(int i = 1; i <= n; i++){
		if(p[i] != -1){
			rs[k] = dfs(p[i]);
			k++;
			//cout << rs[k] << " ";
		}
	}
//	cout << endl;
	sort(rs, rs + k);
	int tmp = rs[k - 1] + rs[k - 2];
	int ans = tmp * tmp;
	for(int i = 0; i <= k - 3; i++){
		ans += rs[i];
	}
	cout << ans << endl;
	return 0;
}


#include <iostream>
#include <vector>
#include <set>

#define N 100010
#define ll long long
using namespace std;

int main() {
    ll n, temp, flag[N] = {0}, num = 1;
    vector<ll> vll;
    set<ll> sll[N];
    vll.push_back(-1);
    cin >> n;
    for (auto i = 0; i < n; i++) {
        cin >> temp;
        vll.push_back(temp);
    }
    for (auto i = 1; i <= n; i++) {
        if (flag[i] == 0) {
            ll j = i;
            flag[j] = 1;
            sll[num].insert(j);
            while (!sll[num].count(vll[j])) {
                sll[num].insert(vll[j]);
                j = vll[j];
                flag[j] = 1;
            }
            num++;
        }
    }
    ll max1 = 0, max2 = 0;
    ll anw = 0;
    for (auto i = 1; i < num; i++) {
        anw += (sll[i].size() * sll[i].size());
        if (sll[i].size() >= max1) {
            max2 = max1;
            max1 = sll[i].size();
        } else if (sll[i].size() >= max2) {
            max2 = sll[i].size();
        }
    }
    anw += (2 * max1 * max2);
    cout << anw << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <set>

#define N 100010
#define ll long long
using namespace std;

int main() {
    int n, temp, flag[N] = {0}, num = 1;
    vector<int> vi;
    set<int> si[N];
    vi.push_back(-1);
    cin >> n;
    for (auto i = 0; i < n; i++) {
        scanf("%d", &temp);
        vi.push_back(temp);
    }
    for (auto i = 1; i <= n; i++) {
        if (!flag[i]) {
            auto j = i;
            flag[j] = 1;
            si[num].insert(j);
            while (si[num].find(vi[j]) == si[num].end()) {
                si[num].insert(vi[j]);
                j = vi[j];
                flag[j] = 1;
            }
            num++;
        }
    }
    ll max1 = 0, max2 = 0;
    ll anw = 0;
    for (auto i = 1; i < num; i++) {
        anw += (si[i].size() * si[i].size());
        if (si[i].size() >= max1) {
            max2 = max1;
            max1 = si[i].size();
        } else if (si[i].size() >= max2) {
            max2 = si[i].size();
        }
    }
    anw -= (max1 * max1);
    anw -= (max2 * max2);
    anw += ((max1 + max2) * (max1 + max2));
    cout << anw << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <set>

#define N 100010
#define ll long long
using namespace std;

int main() {
    ll n, temp, flag[N] = {0}, num = 1;
    vector<ll> vll;
    set<ll> sll[N];
    vll.push_back(-1);
    cin >> n;
    for (auto i = 0; i < n; i++) {
        cin >> temp;
        vll.push_back(temp);
    }
    for (auto i = 1; i <= n; i++) {
        if (flag[i] == 0) {
            ll j = i;
            flag[j] = 1;
            sll[num].insert(j);
            while (!sll[num].count(vll[j])) {
                sll[num].insert(vll[j]);
                j = vll[j];
                flag[j] = 1;
            }
            num++;
        }
    }
    ll max1 = 0, max2 = 0;
    ll anw = 0;
    for (auto i = 1; i < num; i++) {
        anw += (sll[i].size() * sll[i].size());
        if (sll[i].size() >= max1) {
            max2 = max1;
            max1 = sll[i].size();
        } else if (sll[i].size() >= max2) {
            max2 = sll[i].size();
        }
    }
    anw += (2LL * max1 * max2);
    cout << anw << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <set>

#define N 100010
#define ll long long
using namespace std;

int main() {

    ll n, temp, flag[N] = {0}, num = 1;
    vector<ll> vi;
    set<ll> si[N];
    vi.push_back(-1);
    cin >> n;
    for (auto i = 0; i < n; i++) {
        cin >> temp;
        vi.push_back(temp);
    }
    for (auto i = 1; i <= n; i++) {
        if (!flag[i]) {
            auto j = i;
            flag[j] = 1;
            si[num].insert(j);
            while (si[num].find(vi[j]) == si[num].end()) {
                si[num].insert(vi[j]);
                j = vi[j];
                flag[j] = 1;
            }
            num++;
        }
    }
    ll max1 = 0, max2 = 0;
    ll anw = 0;
    for (auto i = 1; i < num; i++) {
        anw += (si[i].size() * si[i].size());
        if (si[i].size() >= max1) {
            max2 = max1;
            max1 = si[i].size();
        } else if (si[i].size() >= max2) {
            max2 = si[i].size();
        }
    }
    anw += (2 * max1 * max2);
    cout << anw << endl;
    return 0;
}


#include <iostream>
#include <vector>
#include <set>

#define N 100010
using namespace std;

int main() {
    int n, temp, flag[N] = {0}, num = 1;
    vector<int> vi;
    set<int> si[N];
    vi.push_back(-1);
    cin >> n;
    for (auto i = 0; i < n; i++) {
        scanf("%d", &temp);
        vi.push_back(temp);
    }
    for (auto i = 1; i <= n; i++) {
        if (!flag[i]) {
            auto j = i;
            flag[j] = 1;
            si[num].insert(j);
            while (si[num].find(vi[j]) == si[num].end()) {
                si[num].insert(vi[j]);
                j = vi[j];
                flag[j] = 1;
            }
            num++;
        }
    }
    int max1 = 0, max2 = 0;
    long long anw = 0;
    for (auto i = 1; i < num; i++) {
        anw += (si[i].size() * si[i].size());
        if (si[i].size() >= max1) {
            max2 = max1;
            max1 = si[i].size();
        } else if (si[i].size() >= max2) {
            max2 = si[i].size();
        }
    }
    anw -= (max1 * max1);
    anw -= (max2 * max2);
    anw += ((max1 + max2) * (max1 + max2));
    cout << anw << endl;
    return 0;
}


#include <iostream>
#include<vector>
#include<string>
#include<set>

using namespace std;

#define LOGD(args...)// printf("D:");fprintf(stdout,args);printf("\n")

vector<bool> is_visit;
vector<int> graph;

void DFS(int i,int& node_count){
    is_visit[i]=true;
    node_count++;
    int child=graph[i];
    if(!is_visit[child]){
        DFS(child,node_count);
    }
}

int main()
{
    //freopen("data.txt","r",stdin);
    int n;
    cin>>n;
    is_visit.insert(is_visit.begin(),n+1,false);
    graph.insert(graph.begin(),n+1,0);
    for(int i=0;i<n;i++){
        int d;
        cin>>d;
        graph[i+1]=d;
    }

    multiset<int,greater<int>> s;
    for(int i=1;i<=n;i++){
        if(!is_visit[i]){
            int node_count=0;
            DFS(i,node_count);
            LOGD("i is %d, count is %d",i,node_count);
            s.insert(node_count);
        }
    }
    int ans=0;
    int i=0;
    for(auto node_count:s){
        if(i==0){
            ans+=node_count;
        }
        else if(i==1){
            ans+=node_count;
            ans=ans*ans;
        }
        else{
            ans=ans+node_count*node_count;
        }
        i++;
    }
    if(i==1){
        ans=ans*ans;
    }
    printf("%d",ans);

    return 0;
}


#include <iostream>
#include<vector>
#include<string>
#include<set>

using namespace std;

#define LOGD(args...)// printf("D:");fprintf(stdout,args);printf("\n")

vector<bool> is_visit;
vector<int> graph;

void DFS(int i,int& node_count){
    is_visit[i]=true;
    node_count++;
    int child=graph[i];
    if(!is_visit[child]){
        DFS(child,node_count);
    }
}

int main()
{
    //freopen("data.txt","r",stdin);
    int n;
    cin>>n;
    is_visit.insert(is_visit.begin(),n+1,false);
    graph.insert(graph.begin(),n+1,0);
    for(int i=0;i<n;i++){
        int d;
        cin>>d;
        graph[i+1]=d;
    }

    multiset<int,greater<int>> s;
    for(int i=1;i<=n;i++){
        if(!is_visit[i]){
            int node_count=0;
            DFS(i,node_count);
            LOGD("i is %d, count is %d",i,node_count);
            s.insert(node_count);
        }
    }
    long long int ans=0;
    int i=0;
    for(auto node_count:s){
        if(i==0){
            ans+=node_count;
        }
        else if(i==1){
            ans+=node_count;
            ans=ans*ans;
        }
        else{
            ans=ans+node_count*node_count;
        }
        i++;
    }
    if(i==1){
        ans=ans*ans;
    }
    printf("%lld",ans);

    return 0;
}


#include <iostream>
#include<vector>
#include<string>
#include<set>

using namespace std;

#define LOGD(args...)// printf("D:");fprintf(stdout,args);printf("\n")

vector<bool> is_visit;
vector<int> graph;

void DFS(int i,int& node_count){
    is_visit[i]=true;
    node_count++;
    int child=graph[i];
    if(!is_visit[child]){
        DFS(child,node_count);
    }
}

int main()
{
    //freopen("data.txt","r",stdin);
    int n;
    cin>>n;
    is_visit.insert(is_visit.begin(),n+1,false);
    graph.insert(graph.begin(),n+1);
    for(int i=0;i<n;i++){
        int d;
        cin>>d;
        graph[i+1]=d;
    }

    multiset<int,greater<int>> s;
    for(int i=1;i<=n;i++){
        if(!is_visit[i]){
            int node_count=0;
            DFS(i,node_count);
            LOGD("i is %d, count is %d",i,node_count);
            s.insert(node_count);
        }
    }
    int ans=0;
    int i=0;
    for(auto node_count:s){
        if(i==0){
            ans+=node_count;
        }
        else if(i==1){
            ans+=node_count;
            ans=ans*ans;
        }
        else{
            ans=ans+node_count*node_count;
        }
        i++;
    }
    if(i==1){
        ans=ans*ans;
    }
    printf("%d",ans);

    return 0;
}


#include <iostream>
#include<vector>
#include<string>
#include<set>

using namespace std;

#define LOGD(args...) printf("D:");fprintf(stdout,args);printf("\n")

vector<bool> is_visit;
vector<int> graph;

void DFS(int i,int& node_count){
    is_visit[i]=true;
    node_count++;
    int child=graph[i];
    if(!is_visit[child]){
        DFS(child,node_count);
    }
}

int main()
{
    //freopen("data.txt","r",stdin);
    int n;
    cin>>n;
    is_visit.insert(is_visit.begin(),n+1,false);
    graph.insert(graph.begin(),n+1);
    for(int i=0;i<n;i++){
        int d;
        cin>>d;
        graph[i+1]=d;
    }

    multiset<int,greater<int>> s;
    for(int i=1;i<=n;i++){
        if(!is_visit[i]){
            int node_count=0;
            DFS(i,node_count);
            LOGD("i is %d, count is %d",i,node_count);
            s.insert(node_count);
        }
    }
    int ans=0;
    int i=0;
    for(auto node_count:s){
        if(i==0){
            ans+=node_count;
        }
        else if(i==1){
            ans+=node_count;
            ans=ans*ans;
        }
        else{
            ans=ans+node_count*node_count;
        }
        i++;
    }
    if(i==1){
        ans=ans*ans;
    }
    printf("%d",ans);

    return 0;
}


#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <algorithm>

#define PI acos(-1)
#define INF 0x3f3f3f3f
#define SCD(a) scanf("%d",&a)
#define SCL(a) scanf("%lld", &a)
#define SCLL(a,b) scanf("%lld%lld", &a, &b)
#define SCDD(a,b) scanf("%d%d",&a,&b)
#define SCF(a) scanf("%lf",&a)
#define PTD(a) printf("%d", a)
#define PTL(a) printf("%lld", a)
#define PTLE(a) printf("%lld\n", a)
#define PTDE(a) printf("%d\n",a)
#define MST(a,b) memset(a, b, sizeof(a))

using namespace std;
typedef long long LL;

const int L = 100010;
LL n, k;
LL ans;

LL vis[L];
vector<LL> v[L];
vector<LL> m;

void run()
{
    int i;
    LL t, j;
    LL cnt = 0;
    for(i=1; i<=n; i++){
        cin>>t;
        v[i].push_back(t);
    }
    for(i=1; i<=n; i++){
        if(vis[i] == 0){
            vis[i] = 1;
            j = i;
            cnt = 1;
            while(v[j][0] != i){
                vis[ v[j][0] ] = 1;
                j = v[j][0];
                cnt++;
                //PTDE(cnt);
            }
            m.push_back(cnt);
        }
    }
    sort(m.begin(), m.end());
    ans = 0;
    LL len = m.size();
    if(len == 1)
        PTLE(m[0] * m[0]);
    else{
        for(i=0; i<len-2; i++){
            ans += m[i] * m[i];
            PTLE(ans);
        }
        ans += (m[len-2] + m[len-1])*( m[len-2] + m[len-1] );
        PTLE(ans);
    }

}

int main()
{
    cin>>n;
    MST(vis, 0);

    run();

    return 0;
}

/*
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;

const int maxn = 1e5 + 5;

ll vis[maxn];
vector<ll>num;
vector<ll>g[maxn];

int main()
{
    ll n; cin >> n;
    for (int i = 1; i <= n; i++)
    {
        ll v; cin >> v;
        g[i].push_back(v);
    }
    for (int i = 1; i <= n; i++)
    {
        if (vis[i] == 0)
        {
            vis[i] = 1;
            ll j = i, count = 1;
            while ((g[j][0] != i))
                vis[g[j][0]] = 1, j = g[j][0], count++;
            num.push_back(count);
        }
    }
    ll len = num.size(), sum = 0;
    sort(num.begin(), num.end());
    if (len == 1)
    {
        cout << num[0]*num[0] << endl;
    }
    else
    {
        for (int i = 0; i < len - 2; i++)
            sum += num[i] * num[i];
        sum += (num[len - 2] + num[len - 1])*(num[len - 2] + num[len - 1]);
        cout << sum << endl;
    }
    return 0;
}
*/


<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
	<FileVersion major="1" minor="6" />
	<Project>
		<Option title="text01" />
		<Option pch_mode="2" />
		<Option compiler="gcc" />
		<Build>
			<Target title="Debug">
				<Option output="bin/Debug/text01" prefix_auto="1" extension_auto="1" />
				<Option object_output="obj/Debug/" />
				<Option type="1" />
				<Option compiler="gcc" />
				<Compiler>
					<Add option="-g" />
				</Compiler>
			</Target>
			<Target title="Release">
				<Option output="bin/Release/text01" prefix_auto="1" extension_auto="1" />
				<Option object_output="obj/Release/" />
				<Option type="1" />
				<Option compiler="gcc" />
				<Compiler>
					<Add option="-O2" />
				</Compiler>
				<Linker>
					<Add option="-s" />
				</Linker>
			</Target>
		</Build>
		<Compiler>
			<Add option="-Wall" />
			<Add option="-fexceptions" />
		</Compiler>
		<Unit filename="main.cpp" />
		<Extensions>
			<code_completion />
			<envvars />
			<debugger />
			<lib_finder disable_auto="1" />
		</Extensions>
	</Project>
</CodeBlocks_project_file>


#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <algorithm>

#define PI acos(-1)
#define INF 0x3f3f3f3f
#define SCD(a) scanf("%d",&a)
#define SCL(a) scanf("%lld", &a)
#define SCLL(a,b) scanf("%lld%lld", &a, &b)
#define SCDD(a,b) scanf("%d%d",&a,&b)
#define SCF(a) scanf("%lf",&a)
#define PTD(a) printf("%d", a)
#define PTL(a) printf("%lld", a)
#define PTLE(a) printf("%lld\n", a)
#define PTDE(a) printf("%d\n",a)
#define MST(a,b) memset(a, b, sizeof(a))

using namespace std;
typedef long long LL;

const int L = 100010;
int n, m, k;
LL ans;

LL p[L];
bool vis[L];
vector< LL > v;

LL getlength(LL i)
{
    if(vis[i])
        return 0;
    vis[i] = true;
    LL t = 0;
    LL x = i;
    while(x != p[i]){
        vis[i] = true;
        t++;
        i = p[i];
        vis[i] = true;
    }
    return t+1;
}

void getmap()
{
    int i;
    LL t;
    int cnt = 0;
    ans = 0;
    v.clear();
    for(i=1; i<=n; i++)
        SCD(p[i]);
    for(i=1; i<=n; i++){
        t = getlength(i);
        if(t == 0)
            continue;
        ans += t * t;
        v.push_back(t);
        cnt++;
    }
    sort(v.begin(),v.end());
    ans += 2 * v[cnt-2] * v[cnt-1];

}

int main()
{
    int i, j;
    SCD(n);
    if(!n){
        PTDE(0);
        return 0;
    }
    MST(vis, false);
    getmap();
    if(n==1){
        PTDE(1);
        return 0;
    }
    PTDE(ans);

    return 0;
}


#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <algorithm>

#define PI acos(-1)
#define INF 0x3f3f3f3f
#define SCD(a) scanf("%d",&a)
#define SCL(a) scanf("%lld", &a)
#define SCLL(a,b) scanf("%lld%lld", &a, &b)
#define SCDD(a,b) scanf("%d%d",&a,&b)
#define SCF(a) scanf("%lf",&a)
#define PTD(a) printf("%d", a)
#define PTL(a) printf("%lld", a)
#define PTLE(a) printf("%lld\n", a)
#define PTDE(a) printf("%d\n",a)
#define MST(a,b) memset(a, b, sizeof(a))

using namespace std;
typedef long long LL;

const int L = 100010;
int n, m, k, ans;

int p[L];
bool vis[L];
vector< int > v;

int getlength(int i)
{
    if(vis[i])
        return 0;
    vis[i] = true;
    int t = 0;
    int x = i;
    while(x != p[i]){
        vis[i] = true;
        t++;
        i = p[i];
        vis[i] = true;
    }
    return t+1;
}

void getmap()
{
    int i, t, cnt = 0;
    ans = 0;
    v.clear();
    for(i=1; i<=n; i++)
        SCD(p[i]);
    for(i=1; i<=n; i++){
        t = getlength(i);
        if(t == 0)
            continue;
        ans += t * t;
        v.push_back(t);
        cnt++;
    }
    sort(v.begin(),v.end());
    ans += 2 * v[cnt-2] * v[cnt-1];

}

int main()
{
    int b, t;
    int i, j, cnt;
    SCD(n);
    MST(vis, false);
    getmap();
    PTDE(ans);

    return 0;
}


#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <algorithm>

#define PI acos(-1)
#define INF 0x3f3f3f3f
#define SCD(a) scanf("%d",&a)
#define SCL(a) scanf("%lld", &a)
#define SCLL(a,b) scanf("%lld%lld", &a, &b)
#define SCDD(a,b) scanf("%d%d",&a,&b)
#define SCF(a) scanf("%lf",&a)
#define PTD(a) printf("%d", a)
#define PTL(a) printf("%lld", a)
#define PTLE(a) printf("%lld\n", a)
#define PTDE(a) printf("%d\n",a)
#define MST(a,b) memset(a, b, sizeof(a))

using namespace std;
typedef long long LL;

const int L = 100010;
int n, m, k, ans;

int p[L];
bool vis[L];
vector< int > v;

int getlength(int i)
{
    if(vis[i])
        return 0;
    vis[i] = true;
    int t = 0;
    int x = i;
    while(x != p[i]){
        vis[i] = true;
        t++;
        i = p[i];
        vis[i] = true;
    }
    return t+1;
}

void getmap()
{
    int i, t, cnt = 0;
    ans = 0;
    v.clear();
    for(i=1; i<=n; i++)
        SCD(p[i]);
    for(i=1; i<=n; i++){
        t = getlength(i);
        if(t == 0)
            continue;
        ans += t * t;
        v.push_back(t);
        cnt++;
    }
    sort(v.begin(),v.end());
    ans += 2 * v[cnt-2] * v[cnt-1];

}

int main()
{
    int b, t;
    int i, j, cnt;
    SCD(n);
    if(!n){
        PTDE(0);
        return 0;
    }
    MST(vis, false);
    getmap();
    if(n==1){
        PTDE(1);
        return 0;
    }
    PTDE(ans);

    return 0;
}


#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <algorithm>

#define PI acos(-1)
#define INF 0x3f3f3f3f
#define SCD(a) scanf("%d",&a)
#define SCL(a) scanf("%lld", &a)
#define SCLL(a,b) scanf("%lld%lld", &a, &b)
#define SCDD(a,b) scanf("%d%d",&a,&b)
#define SCF(a) scanf("%lf",&a)
#define PTD(a) printf("%d", a)
#define PTL(a) printf("%lld", a)
#define PTLE(a) printf("%lld\n", a)
#define PTDE(a) printf("%d\n",a)
#define MST(a,b) memset(a, b, sizeof(a))

using namespace std;
typedef long long LL;

const int L = 100010;
int n, m, k, ans;

int p[L];
bool vis[L];
vector< int > v;

int getlength(int i)
{
    if(vis[i])
        return 0;
    vis[i] = true;
    int t = 0;
    int x = i;
    while(x != p[i]){
        vis[i] = true;
        t++;
        i = p[i];
        vis[i] = true;
    }
    return t+1;
}

void getmap()
{
    int i, t, cnt = 0;
    ans = 0;
    v.clear();
    for(i=1; i<=n; i++)
        SCD(p[i]);
    for(i=1; i<=n; i++){
        t = getlength(i);
        if(t == 0)
            continue;
        ans += t * t;
        v.push_back(t);
        cnt++;
    }
    sort(v.begin(),v.end());
    ans += 2 * v[cnt-2] * v[cnt-1];

}

int main()
{
    int b, t;
    int i, j, cnt;
    SCD(n);
    MST(vis, false);
    getmap();
    if(n==1){
        PTDE(1);
        return 0;
    }
    PTDE(ans);

    return 0;
}


#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <algorithm>

#define PI acos(-1)
#define INF 0x3f3f3f3f
#define SCD(a) scanf("%d",&a)
#define SCL(a) scanf("%lld", &a)
#define SCLL(a,b) scanf("%lld%lld", &a, &b)
#define SCDD(a,b) scanf("%d%d",&a,&b)
#define SCF(a) scanf("%lf",&a)
#define PTD(a) printf("%d", a)
#define PTL(a) printf("%lld", a)
#define PTLE(a) printf("%lld\n", a)
#define PTDE(a) printf("%d\n",a)
#define MST(a,b) memset(a, b, sizeof(a))

using namespace std;
typedef long long LL;

const int L = 100010;
LL n, k;
LL ans;

LL vis[L];
vector<LL> v[L];
vector<LL> m;

void run()
{
    int i;
    LL t, j;
    LL cnt = 0;
    for(i=1; i<=n; i++){
        cin>>t;
        v[i].push_back(t);
    }
    for(i=1; i<=n; i++){
        if(vis[i] == 0){
            vis[i] = 1;
            j = i;
            cnt = 1;
            while(v[j][0] != i){
                vis[ v[j][0] ] = 1;
                j = v[j][0];
                cnt++;
                //PTDE(cnt);
            }
            m.push_back(cnt);
        }
    }
    sort(m.begin(), m.end());
    ans = 0;
    LL len = m.size();
    if(len == 1)
        PTLE(m[0] * m[0]);
    else{
        for(i=0; i<len-2; i++){
            ans += m[i] * m[i];
            //PTLE(ans);
        }
        ans += (m[len-2] + m[len-1])*( m[len-2] + m[len-1] );
        PTLE(ans);
    }

}

int main()
{
    cin>>n;
    MST(vis, 0);

    run();

    return 0;
}

/*
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
typedef long long ll;

const int maxn = 1e5 + 5;

ll vis[maxn];
vector<ll>num;
vector<ll>g[maxn];

int main()
{
    ll n; cin >> n;
    for (int i = 1; i <= n; i++)
    {
        ll v; cin >> v;
        g[i].push_back(v);
    }
    for (int i = 1; i <= n; i++)
    {
        if (vis[i] == 0)
        {
            vis[i] = 1;
            ll j = i, count = 1;
            while ((g[j][0] != i))
                vis[g[j][0]] = 1, j = g[j][0], count++;
            num.push_back(count);
        }
    }
    ll len = num.size(), sum = 0;
    sort(num.begin(), num.end());
    if (len == 1)
    {
        cout << num[0]*num[0] << endl;
    }
    else
    {
        for (int i = 0; i < len - 2; i++)
            sum += num[i] * num[i];
        sum += (num[len - 2] + num[len - 1])*(num[len - 2] + num[len - 1]);
        cout << sum << endl;
    }
    return 0;
}
*/


// Created by martinezdiego on 31/5/19

#include <bits/stdc++.h>

using namespace std;

#define  N 100005
int cnt;
vector<int> adj[N];
bool visited[N];

void dfs(int n) {
  if (visited[n]) return;
  visited[n] = true;
  cnt++;
  for (auto i : adj[n]) dfs(i);
}

int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int p;
    cin >> p;
    adj[i].push_back(p);
    adj[p].push_back(i);
  }
  vector<int> sz;
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    cnt = 0;
    dfs(i);
    sz.push_back(cnt);
  }
  sort(sz.begin(),sz.end());
  int l = sz.size();
  long long ans = 0;
  if (l > 1) ans = (sz[l-1] + sz[l-2]) * (sz[l-1] + sz[l-2]);
  else ans = sz[0] * sz[0];
  for (int i = 0; i < l - 2; i++) {
    ans += sz[i]*sz[i];
  }
  cout << ans << '\n';
  return 0;
}


// Created by martinezdiego on 31/5/19

#include <bits/stdc++.h>

using namespace std;

#define  N 100005
int cnt;
vector<int> adj[N];
bool visited[N];

void dfs(int n) {
  if (visited[n]) return;
  visited[n] = true;
  cnt++;
  for (auto i : adj[n]) dfs(i);
}

int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int p;
    cin >> p;
    adj[i].push_back(p);
    adj[p].push_back(i);
  }
  vector<int> sz;
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    cnt = 0;
    dfs(i);
    sz.push_back(cnt);
  }
  sort(sz.begin(),sz.end());
  int l = sz.size();
  long long ans = 0;
  if (l > 1) ans = 2*sz[l-1]*sz[l-2];
  else ans = sz[0] * sz[0];
  for (int i = 0; i < l - 2; i++) {
    ans += sz[i];
  }
  cout << ans << '\n';
  return 0;
}


// Created by martinezdiego on 31/5/19

#include <bits/stdc++.h>

using namespace std;

#define  N 100005
int cnt;
vector<int> adj[N];
bool visited[N];

void dfs(int n) {
  if (visited[n]) return;
  visited[n] = true;
  cnt++;
  for (auto i : adj[n]) dfs(i);
}

int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int p;
    cin >> p;
    adj[i].push_back(p);
    adj[p].push_back(i);
  }
  vector<int> sz;
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    cnt = 0;
    dfs(i);
    sz.push_back(cnt);
  }
  sort(sz.begin(),sz.end());
  int l = sz.size();
  long long ans = 0;
  if (l > 1)
    ans = (long long)(sz[l-1] + sz[l-2]) * (sz[l-1] + sz[l-2]);
  else
    ans = (long long) sz[0] * sz[0];
  for (int i = 0; i < l - 2; i++) {
    ans += (long long) sz[i] * sz[i];
  }
  cout << ans << '\n';
  return 0;
}


// Created by martinezdiego on 31/5/19

#include <bits/stdc++.h>

using namespace std;

#define  N 100005
int cnt;
vector<int> adj[N];
bool visited[N];

void dfs(int n) {
  if (visited[n]) return;
  visited[n] = true;
  cnt++;
  for (auto i : adj[n]) dfs(i);
}

int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int p;
    cin >> p;
    adj[i].push_back(p);
    adj[p].push_back(i);
  }
  vector<int> sz;
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    cnt = 0;
    dfs(i);
    sz.push_back(cnt);
  }
  sort(sz.begin(),sz.end());
  int l = sz.size();
  long long ans = (sz[l-1] + sz[l-2]) * (sz[l-1] + sz[l-2]);
  for (int i = 0; i < sz.size() - 2; i++) {
    ans += sz[i];
  }
  cout << ans << '\n';
  return 0;
}


// Created by martinezdiego on 31/5/19

#include <bits/stdc++.h>

using namespace std;

#define  N 100005
int cnt;
vector<int> adj[N];
bool visited[N];

void dfs(int n) {
  if (visited[n]) return;
  visited[n] = true;
  cnt++;
  for (auto i : adj[n]) dfs(i);
}

int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int p;
    cin >> p;
    adj[i].push_back(p);
    adj[p].push_back(i);
  }
  vector<int> sz;
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    cnt = 0;
    dfs(i);
    sz.push_back(cnt);
  }
  sort(sz.begin(),sz.end());
  int l = sz.size();
  long long ans = 0;
  if (l > 1) ans = (sz[l-1] + sz[l-2]) * (sz[l-1] + sz[l-2]);
  else ans = sz[0] * sz[0];
  for (int i = 0; i < l - 2; i++) {
    ans += sz[i];
  }
  cout << ans << '\n';
  return 0;
}


// Created by martinezdiego on 31/5/19

#include <bits/stdc++.h>

using namespace std;

#define  N 100005
int cnt;
vector<int> adj[N];
bool visited[N];

void dfs(int n) {
  if (visited[n]) return;
  visited[n] = true;
  cnt++;
  for (auto i : adj[n]) dfs(i);
}

int main() {
  ios_base::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int p;
    cin >> p;
    adj[i].push_back(p);
    adj[p].push_back(i);
  }
  vector<int> sz;
  for (int i = 1; i <= n; i++) {
    if (visited[i]) continue;
    cnt = 0;
    dfs(i);
    sz.push_back(cnt);
  }
  sort(sz.begin(),sz.end());
  int l = sz.size();
  long long ans = 0;
  if (l > 1) ans = (sz[l-1] + sz[l-2]) * (sz[l-1] + sz[l-2]);
  else ans = sz[0];
  for (int i = 0; i < l - 2; i++) {
    ans += sz[i];
  }
  cout << ans << '\n';
  return 0;
}


#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n;
    cin>>n;

    if(n==0){
        cout<<"0";
        return 0;
    }

    if(n==1){
        cout<<"1";
        return 0;
    }

    int A[n];
    bool visited[n];

    for(int i=0; i<n; i++){
        cin>>A[i];
        visited[i]=false;
    }
    //cout<<endl;
    long long int max1=1,max2=0;
    long long int ans = 0;

    for(int i=0; i<n; i++){
        if(visited[i]) continue;
        int j = i;
        visited[j] = true;
        j = A[j]-1;
        //visited[j] = true;
        long long int l=1;
        while(j!=i){
            //cout<<i<<"+"<<endl;
            l++;
            visited[j] = true;
            j = A[j]-1;

        }

        //k+=l;
        ans+= l*l;
        //cout<<l<<endl;
        if(l>max1){
            if (i>0) max2 = max1;
            max1 = l;

        }
        else if(l>max2){
            max2 = l;
        }
    }

    ans+=2*max1*max2;
    cout<<ans;

    return 0;
}


#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n;
    cin>>n;

    if(n==0){
        cout<<"0";
        return 0;
    }

    if(n==1){
        cout<<"1";
        return 0;
    }

    int A[n];
    bool visited[n];

    for(int i=0; i<n; i++){
        cin>>A[i];
        visited[i]=false;
    }
    //cout<<endl;
    long long int max1=1,max2=0;
    long long int ans = 0;

    for(int i=0; i<n; i++){
        if(visited[i]) continue;
        int j = i;
        visited[j] = true;
        j = A[j]-1;
        //visited[j] = true;
        long long int l=1;
        while(j!=i){
            //cout<<i<<"+"<<endl;
            l++;
            visited[j] = true;
            j = A[j]-1;

        }

        //k+=l;
        ans+= l*l;
        //cout<<l<<endl;
        if(l>max1){
            max2 = max1;
            max1 = l;

        }
        else if(l>max2){
            max2 = l;
        }
    }

    ans+=2*max1*max2;
    cout<<ans;

    return 0;
}


#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n;
    cin>>n;

    if(n==0){
        cout<<"0";
        return 0;
    }

    if(n==1){
        cout<<"1";
        return 0;
    }

    int A[n];
    bool visited[n];

    for(int i=0; i<n; i++){
        cin>>A[i];
        visited[i]=false;
    }
    //cout<<endl;
    long long int max1=1,max2=0;
    long long int ans = 0;

    for(int i=0; i<n; i++){
        if(visited[i]) continue;
        int j = i;
        visited[j] = true;
        j = A[j]-1;
        //visited[j] = true;
        long long int l=1;
        while(j!=i){
            //cout<<i<<"+"<<endl;
            l++;
            visited[j] = true;
            j = A[j]-1;

        }

        //k+=l;
        ans+= l*l;
        //cout<<l<<endl;
        if(l>max1){
            if (max2!=0) max2 = max1;
            max1 = l;

        }
        else if(l>max2){
            max2 = l;
        }
    }

    ans+=2*max1*max2;
    cout<<ans;

    return 0;
}


#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n;
    cin>>n;

    if(n==0){
        cout<<"0";
        return 0;
    }

    if(n==1){
        cout<<"1";
        return 0;
    }

    int A[n];
    bool visited[n];

    for(int i=0; i<n; i++){
        cin>>A[i];
        visited[i]=false;
    }
    //cout<<endl;
    long long int max1=1,max2=0;
    long long int ans = 0;

    for(int i=0; i<n; i++){
        if(visited[i]) continue;
        int j = i;
        visited[j] = true;
        j = A[j]-1;
        //visited[j] = true;
        long long int l=1;
        while(j!=i){
            //cout<<i<<"+"<<endl;
            l++;
            visited[j] = true;
            j = A[j]-1;

        }

        //k+=l;
        ans+= l*l;
        //cout<<l<<endl;
        if(l>max1){
            max1 = l;
        }
        else if(l>max2){
            max2 = l;
        }
    }

    ans+=2*max1*max2;
    cout<<ans;

    return 0;
}


#include <iostream>
using namespace std;

int main() {
    // your code goes here
    int n;
    cin>>n;

    if(n==0){
        cout<<"0";
        return 0;
    }

    if(n==1){
        cout<<"1";
        return 0;
    }

    int A[n];
    bool visited[n];

    for(int i=0; i<n; i++){
        cin>>A[i];
        visited[i]=false;
    }
    //cout<<endl;
    int max1=1,max2=0;
    int ans = 0;

    for(int i=0; i<n; i++){
        if(visited[i]) continue;
        int j = i;
        visited[j] = true;
        j = A[j]-1;
        //visited[j] = true;
        int l=1;
        while(j!=i){
            //cout<<i<<"+"<<endl;
            l++;
            visited[j] = true;
            j = A[j]-1;

        }

        //k+=l;
        ans+= l*l;
        //cout<<l<<endl;
        if(l>max1){
            max1 = l;
        }
        else if(l>max2){
            max2 = l;
        }
    }

    ans+=2*max1*max2;
    cout<<ans;

    return 0;
}


#include <cstdarg>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long num;

inline void RN(num& v) {
    bool f = false; char ch = getchar(); v = 0;
    while(ch < '0') f = (ch == '-'), ch = getchar();
    while(ch >= '0') v = v * 10 + ch - '0', ch = getchar();
    if(f) v = -v;
}
template <typename T>
void print(T t) { cout << t; }
template<typename T, typename... Args>
void print(T t, Args... args) { cout << t; print(args...); }
#define _for(i,s,e) for(i=s;i<e;i++)
#define _fok(i,s,e,k) for(i=s;i<e;i+=k)
//
// gi gi gi gi gi gi gi gi gi gi gi gi
//
const int SZ = 1e5 + 10;
num a[SZ];
num i, j, c;
num vis[SZ];
int main() {
    #ifdef GIGI
        freopen("in", "r", stdin);
    #endif
    num n;
    RN(n);
    _for(i,0,n) RN(a[i+1]);
    num k = n;
    vector<num> s;
    num sumd = 0, d, sumdd = 0, vs=0;
    num z = 1, z1, zz;
    while(vs < n) {
        d = 1;
        while(a[z] != 999999) {
            if(!vis[z]) {
                vis[z] = 1;
                if(a[a[z]] != z) d++;
                //print(z, "-", a[z], "\n");
                z1 = a[z];
                a[z] = 999999;
                z = z1;
                vs++;
            }
        }
        s.push_back(d);
        while(vis[z]) z++;
    }
    sort(s.rbegin(), s.rend());
    //for(auto vv:s) print(vv, " "); print("\n");
    if(s.size() == 2) {
        s[0] += s[1];
        s[1] = 0;
    } else if(s.size() > 2) {
        s[0] += s[1];
        s[0] += s[2];
        s[1] = s[2] = 0;
    }
    for(auto vv: s) sumd += vv * vv;
    print(sumd, "\n");
}


#include <cstdarg>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long num;

inline void RN(num& v) {
    bool f = false; char ch = getchar(); v = 0;
    while(ch < '0') f = (ch == '-'), ch = getchar();
    while(ch >= '0') v = v * 10 + ch - '0', ch = getchar();
    if(f) v = -v;
}
template <typename T>
void print(T t) { cout << t; }
template<typename T, typename... Args>
void print(T t, Args... args) { cout << t; print(args...); }
#define _for(i,s,e) for(i=s;i<e;i++)
#define _fok(i,s,e,k) for(i=s;i<e;i+=k)
//
// gi gi gi gi gi gi gi gi gi gi gi gi
//
const int SZ = 1e5 + 10;
num a[SZ];
num i, j, c;
num vis[SZ];
int main() {
    #ifdef GIGI
        freopen("in", "r", stdin);
    #endif
    num n;
    RN(n);
    _for(i,0,n) RN(a[i + 1]);
    vector< pair<num, num> > s;
    num sumd = 0, d, cycle;
    num z = 1;
    while(z <= n) {
        d = 0, cycle = 0;
        while(!vis[z]) {
            vis[z] = 1;
            if(a[z] != z || (a[z] == z && a[a[z]] == z)) d++;
            if(vis[a[z]]) cycle = 1;
            //print(z, "-", a[z], "-", a[a[z]], " ", d, "\n");
            z = a[z];
        }
        s.push_back(make_pair(d, cycle));
        while(vis[z] && z <= n) z++;
    }
    sort(s.rbegin(), s.rend());
    //for(auto vv:s) print(vv.first, " ", vv.second); print(sumd, "\n");
    num sk = 0;
    _for(i, 1, s.size()) {
        if(!(s[0].second && s[i].second)) { sk++; s[0].first += s[i].first; s[i].first = 0; s[0].second = 0; }
        if(s[0].second && s[i].second) { sk+=2; s[0].first += s[i].first; s[i].first = 0; }
        if(sk >= 2) break;
    }
    for(auto vv: s) sumd += vv.first * vv.first;
    print(sumd, "\n");
}


#include <cstdarg>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long num;

inline void RN(num& v) {
    bool f = false; char ch = getchar(); v = 0;
    while(ch < '0') f = (ch == '-'), ch = getchar();
    while(ch >= '0') v = v * 10 + ch - '0', ch = getchar();
    if(f) v = -v;
}
template <typename T>
void print(T t) { cout << t; }
template<typename T, typename... Args>
void print(T t, Args... args) { cout << t; print(args...); }
#define _for(i,s,e) for(i=s;i<e;i++)
#define _fok(i,s,e,k) for(i=s;i<e;i+=k)
//
// gi gi gi gi gi gi gi gi gi gi gi gi
//
const int SZ = 1e5 + 10;
num a[SZ];
num i, j, c;
num vis[SZ];
int main() {
    #ifdef GIGI
        freopen("in", "r", stdin);
    #endif
    num n;
    RN(n);
    _for(i,0,n) RN(a[i+1]);
    num k = n;
    vector<num> s;
    num sumd = 0, d, sumdd = 0, vs=0;
    num z = 1, z1, zz;
    while(vs < n) {
        d = 1;
        while(a[z] != 999999) {
            if(!vis[z]) {
                vis[z] = 1;
                if(a[a[z]] != z) d++;
                //print(z, "-", a[z], "\n");
                z1 = a[z];
                a[z] = 999999;
                z = z1;
                vs++;
            }
        }
        s.push_back(d);
        while(vis[z]) z++;
    }
    sort(s.rbegin(), s.rend());
    //for(auto vv:s) print(vv, " "); print("\n");
    if(s.size() == 2) {
        if(s[1] >= 2) { s[1] -= 2; s[0] += 2; }
        else { s[1] -= 1; s[0] += 1; }
    } else if(s.size() >= 2) {
        s[0] += 2;
        s[1] -= 1;
        s[2] -= 1;
    }
    for(auto vv: s) sumd += vv * vv;
    print(sumd, "\n");
}


#include <cstdarg>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long num;

inline void RN(num& v) {
    bool f = false; char ch = getchar(); v = 0;
    while(ch < '0') f = (ch == '-'), ch = getchar();
    while(ch >= '0') v = v * 10 + ch - '0', ch = getchar();
    if(f) v = -v;
}
template <typename T>
void print(T t) { cout << t; }
template<typename T, typename... Args>
void print(T t, Args... args) { cout << t; print(args...); }
#define _for(i,s,e) for(i=s;i<e;i++)
#define _fok(i,s,e,k) for(i=s;i<e;i+=k)
//
// gi gi gi gi gi gi gi gi gi gi gi gi
//
const int SZ = 1e5 + 10;
num a[SZ];
num i, j, c;
num vis[SZ];
int main() {
    #ifdef GIGI
        freopen("in", "r", stdin);
    #endif
    num n;
    RN(n);
    _for(i,0,n) RN(a[i+1]);
    num k = n;
    vector<num> s;
    num sumd = 0, d, sumdd = 0, vs=0;
    num z = 1, z1, zz;
    while(vs < n) {
        d = 1;
        while(a[z] != 999999) {
            if(!vis[z]) {
                if(a[a[z]] != z) d++;
                vis[z] = 1;
                //print(z, "-", a[z], "\n");
                z1 = a[z];
                a[z] = 999999;
                z = z1;
                vs++;
            }
        }
        sumdd += d * d;
        s.push_back(d);
        while(vis[z]) z++;
    }
    sort(s.rbegin(), s.rend());
    //for(auto vv:s) print(vv, " "); print("\n");
    if(s.size() == 1)
        print(sumdd, "\n");
    else {
        sumdd -= s[0] * s[0];
        sumdd -= s[1] * s[1];
        print(sumdd + pow(s[0] + s[1], 2), "\n");
    }
}


#include <cstdarg>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long num;

inline void RN(num& v) {
    bool f = false; char ch = getchar(); v = 0;
    while(ch < '0') f = (ch == '-'), ch = getchar();
    while(ch >= '0') v = v * 10 + ch - '0', ch = getchar();
    if(f) v = -v;
}
template <typename T>
void print(T t) { cout << t; }
template<typename T, typename... Args>
void print(T t, Args... args) { cout << t; print(args...); }
#define _for(i,s,e) for(i=s;i<e;i++)
#define _fok(i,s,e,k) for(i=s;i<e;i+=k)
//
// gi gi gi gi gi gi gi gi gi gi gi gi
//
const int SZ = 1e5 + 10;
num a[SZ];
num i, j, c;
int main() {
    #ifdef GIGI
        freopen("in", "r", stdin);
    #endif
    num n;
    RN(n);
    _for(i,0,n) RN(a[i+1]);
    num k = n;
    vector<num> s;
    num sumd = 0, d, sumdd = 0;
    num z = 1;
    while(sumd < n) {
        d = 1;
        while(a[z] < 999999) { z = a[z]; a[z] = 999999; d++; }
        sumd += d;
        sumdd += d * d;
        s.push_back(d);
    }
    sort(s.rbegin(), s.rend());
    if(s.size() == 1)
        print(sumdd, "\n");
    else if(s.size() == 2) {
        sumdd -= s[0] * s[0];
        sumdd -= s[1] * s[1];
        print(sumdd + pow(s[0] + s[1], 2), "\n");
    }
    else if(s.size() >= 2) {
        sumdd -= s[0] * s[0];
        sumdd -= s[1] * s[1];
        sumdd -= s[2] * s[2];
        print(sumdd + pow(s[0] + s[1] + s[2], 2), "\n");
    }
}


#include <cstdarg>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long num;

inline void RN(num& v) {
    bool f = false; char ch = getchar(); v = 0;
    while(ch < '0') f = (ch == '-'), ch = getchar();
    while(ch >= '0') v = v * 10 + ch - '0', ch = getchar();
    if(f) v = -v;
}
template <typename T>
void print(T t) { cout << t; }
template<typename T, typename... Args>
void print(T t, Args... args) { cout << t; print(args...); }
#define _for(i,s,e) for(i=s;i<e;i++)
#define _fok(i,s,e,k) for(i=s;i<e;i+=k)
//
// gi gi gi gi gi gi gi gi gi gi gi gi
//
const int SZ = 1e5 + 10;
num a[SZ];
num i, j, c;
num vis[SZ];
int main() {
    #ifdef GIGI
        freopen("in", "r", stdin);
    #endif
    num n;
    RN(n);
    _for(i,0,n) RN(a[i+1]);
    num k = n;
    vector< pair<num, num> > s;
    num sumd = 0, d, sumdd = 0, vs=0, cycle, cyclez;
    num z = 1, z1, zz;
    while(vs < n && z <= n) {
        d = 0;
        cycle = 0;
        while(!vis[z]) {
            vis[z] = 1;
            if(a[z] != z || (a[z] == z && a[a[z]] == z)) d++;
            if(vis[a[z]]) cycle = 1;
            //print(z, "-", a[z], "-", a[a[z]], " ", d, "\n");
            z = a[z];
            vs++;
        }
        s.push_back(make_pair(d, cycle));
        while(vis[z] && z <= n) z++;
    }
    sort(s.rbegin(), s.rend());
    //for(auto vv:s) print(vv.first, " ", vv.second); print(sumd, "\n");
    num sk = 0;
    _for(i, 1, s.size()) {
        if(!(s[0].second && s[i].second)) { sk++; s[0].first += s[i].first; s[i].first = 0; s[0].second = 0; }
        if(s[0].second && s[i].second) { sk+=2; s[0].first += s[i].first; s[i].first = 0; }
        if(sk == 2) break;
    }
    for(auto vv: s) sumd += vv.first * vv.first;
    print(sumd, "\n");
}


#include <cstdarg>
#include <cmath>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
typedef long long num;

inline void RN(num& v) {
    bool f = false; char ch = getchar(); v = 0;
    while(ch < '0') f = (ch == '-'), ch = getchar();
    while(ch >= '0') v = v * 10 + ch - '0', ch = getchar();
    if(f) v = -v;
}
template <typename T>
void print(T t) { cout << t; }
template<typename T, typename... Args>
void print(T t, Args... args) { cout << t; print(args...); }
#define _for(i,s,e) for(i=s;i<e;i++)
#define _fok(i,s,e,k) for(i=s;i<e;i+=k)
//
// gi gi gi gi gi gi gi gi gi gi gi gi
//
const int SZ = 1e5 + 10;
num a[SZ];
num i, j, c;
num vis[SZ];
int main() {
    #ifdef GIGI
        freopen("in", "r", stdin);
    #endif
    num n;
    RN(n);
    _for(i,0,n) RN(a[i+1]);
    num k = n;
    vector< pair<num, num> > s;
    num sumd = 0, d, sumdd = 0, vs=0, cycle, cyclez;
    num z = 1, z1, zz;
    while(vs < n && z <= n) {
        d = 0;
        cycle = 0;
        while(!vis[z]) {
            vis[z] = 1;
            if(a[z] != z || (a[z] == z && a[a[z]] == z)) d++;
            if(z == a[a[z]]) cycle = 1;
            //print(z, "-", a[z], "-", a[a[z]], " ", d, "\n");
            z = a[z];
            vs++;
        }
        s.push_back(make_pair(d, cycle));
        while(vis[z] && z <= n) z++;
    }
    sort(s.rbegin(), s.rend());
    //for(auto vv:s) print(vv.first, " "); print(sumd, "\n");
    num sk = 0;
    _for(i, 1, s.size()) {
        if(!(s[0].second && s[i].second)) { sk++; s[0].first += s[i].first; s[i].first = 0; s[0].second = 0; }
        if(s[0].second && s[i].second) { sk+=2; s[0].first += s[i].first; s[i].first = 0; }
        if(sk == 2) break;
    }
    for(auto vv: s) sumd += vv.first * vv.first;
    print(sumd, "\n");
}


#include <bits/stdc++.h>
using namespace std;

#define forn(i,n)      for(int i = 0 ; i < int(n) ; i++)
#define fors(i,s,n)    for(int i = int(s) ; i < int(n) ; i++)
#define ford(i,s,n)    for(int i = int(n-1) ; i >= int(s) ; i--)
#define D(a)           cerr << #a << " = " << a << endl;
#define sz(a)          int((a).size())
#define eb             emplace_back
typedef long long int  ll;
typedef vector<int>    vi;
typedef pair<int,int>  pii;

vi *adj; bool *vis;
int c, p = 0, *v;

void dfs(int n){
	vis[n] = 1;
	for(auto v : adj[n]) if(!vis[v]) dfs(v);
	c++;
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	int n; cin >> n;
	adj = new vi[n];
	vis = new bool[n];
	v = new int[n];
	forn(i,n){
		int x; cin >> x;
		adj[i].eb(x-1);
	}
	forn(i,n) vis[i] = 0;
	forn(i,n) if(!vis[i]){
		c = 0;
		dfs(i);
		v[p++] = c;
	}
	int a = 0, b = 0, *aa = 0, *bb = 0;
	forn(i,p){
		if(v[i] > a){
			b = a;
			bb = aa;
			a = v[i];
			aa = v+i;
		}
		else if(v[i] > b){
			b = v[i];
			bb = v+i;
		}
	}
	ll r = (a+b);
	r *= r;
	forn(i,n) if(v+i != aa && v+i != bb) r += ll(v[i]*v[i]);
	cout << r << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define forn(i,n)      for(int i = 0 ; i < int(n) ; i++)
#define fors(i,s,n)    for(int i = int(s) ; i < int(n) ; i++)
#define ford(i,s,n)    for(int i = int(n-1) ; i >= int(s) ; i--)
#define D(a)           cerr << #a << " = " << a << endl;
#define sz(a)          int((a).size())
#define eb             emplace_back
typedef long long int  ll;
typedef vector<int>    vi;
typedef pair<int,int>  pii;

vi *adj; bool *vis;
int c, p = 0, *v;

void dfs(int n){
	vis[n] = 1;
	for(auto v : adj[n]) if(!vis[v]) dfs(v);
	c++;
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	int n; cin >> n;
	adj = new vi[n];
	vis = new bool[n];
	v = new int[n];
	forn(i,n){
		int x; cin >> x;
		adj[i].eb(x-1);
	}
	forn(i,n) vis[i] = 0;
	forn(i,n) if(!vis[i]) {
		c = 0;
		dfs(i);
		v[p++] = c;
	}
	int a = 0, b = 0, *aa, *bb;
	forn(i,p){
		if(v[i] > a){
			b = a;
			bb = aa;
			a = v[i];
			aa = v+i;
		}
		else if(v[i] > b){
			b = v[i];
			bb = v+i;
		}
	}
	int r = (a+b)*(a+b);
	forn(i,n) if(v+i != aa && v+i != bb) r += v[i]*v[i];
	cout << r << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define forn(i,n)      for(int i = 0 ; i < int(n) ; i++)
#define fors(i,s,n)    for(int i = int(s) ; i < int(n) ; i++)
#define ford(i,s,n)    for(int i = int(n-1) ; i >= int(s) ; i--)
#define D(a)           cerr << #a << " = " << a << endl;
#define sz(a)          int((a).size())
#define eb             emplace_back
typedef long long int  ll;
typedef vector<int>    vi;
typedef pair<int,int>  pii;

vi *adj; bool *vis;
int c, p = 0, *v;

void dfs(int n){
	vis[n] = 1;
	for(auto v : adj[n]) if(!vis[v]) dfs(v);
	c++;
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	int n; cin >> n;
	adj = new vi[n];
	vis = new bool[n];
	v = new int[n];
	forn(i,n){
		int x; cin >> x;
		adj[i].eb(x-1);
	}
	forn(i,n) vis[i] = 0;
	forn(i,n) if(!vis[i]) {
		c = 0;
		dfs(i);
		v[p++] = c;
	}
	int a = 0, b = 0, *aa = 0, *bb = 0;
	forn(i,p){
		if(v[i] > a){
			b = a;
			bb = aa;
			a = v[i];
			aa = v+i;
		}
		else if(v[i] > b){
			b = v[i];
			bb = v+i;
		}
	}
	ll r = (a+b)*(a+b);
	forn(i,n) if(v+i != aa && v+i != bb) r += v[i]*v[i];
	cout << r << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define forn(i,n)      for(int i = 0 ; i < int(n) ; i++)
#define fors(i,s,n)    for(int i = int(s) ; i < int(n) ; i++)
#define ford(i,s,n)    for(int i = int(n-1) ; i >= int(s) ; i--)
#define D(a)           cerr << #a << " = " << a << endl;
#define sz(a)          int((a).size())
#define eb             emplace_back
typedef long long int  ll;
typedef vector<int>    vi;
typedef pair<int,int>  pii;

vi *adj; bool *vis;
int c, p = 0, *v;

void dfs(int n){
	vis[n] = 1;
	for(auto v : adj[n]) if(!vis[v]) dfs(v);
	c++;
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	int n; cin >> n;
	adj = new vi[n];
	vis = new bool[n];
	v = new int[n];
	forn(i,n){
		int x; cin >> x;
		adj[i].eb(x-1);
	}
	forn(i,n) vis[i] = 0;
	forn(i,n) if(!vis[i]) {
		c = 0;
		dfs(i);
		v[p++] = c;
	}
	int a = 0, b = 0, *aa, *bb;
	forn(i,n){
		if(v[i] > a){
			b = a;
			bb = aa;
			a = v[i];
			aa = v+i;
		}
		else if(v[i] > b){
			b = v[i];
			bb = v+i;
		}
	}
	int r = (a+b)*(a+b);
	forn(i,n) if(v+i != aa && v+i != bb) r += v[i]*v[i];
	cout << r << endl;
	return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define forn(i,n)      for(int i = 0 ; i < int(n) ; i++)
#define fors(i,s,n)    for(int i = int(s) ; i < int(n) ; i++)
#define ford(i,s,n)    for(int i = int(n-1) ; i >= int(s) ; i--)
#define D(a)           cerr << #a << " = " << a << endl;
#define sz(a)          int((a).size())
#define eb             emplace_back
typedef long long int  ll;
typedef vector<int>    vi;
typedef pair<int,int>  pii;

vi *adj; bool *vis;
int c, p = 0, *v;

void dfs(int n){
	vis[n] = 1;
	for(auto v : adj[n]) if(!vis[v]) dfs(v);
	c++;
}

int main() {
	ios_base::sync_with_stdio(0); cin.tie(0);
	int n; cin >> n;
	adj = new vi[n];
	vis = new bool[n];
	v = new int[n];
	forn(i,n){
		int x; cin >> x;
		adj[i].eb(x-1);
	}
	forn(i,n) vis[i] = 0;
	forn(i,n) if(!vis[i]){
		c = 0;
		dfs(i);
		v[p++] = c;
	}
	int a = 0, b = 0, *aa = 0, *bb = 0;
	forn(i,p){
		if(v[i] > a){
			b = a;
			bb = aa;
			a = v[i];
			aa = v+i;
		}
		else if(v[i] > b){
			b = v[i];
			bb = v+i;
		}
	}
	ll r = a+b;
	r *= r;
	forn(i,p) if(v+i != aa && v+i != bb) r += ll(v[i]*v[i]);
	cout << r << endl;
	return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second

using namespace std;

const int N=1e6+7;

//scanf("%d",&);
int n,vis[N],visId,u,cnt[N],c;
vector<int> graph[N];

void dfs(int x){
    vis[x]=visId;
    cnt[visId]++;
    for(int i:graph[x])
        if(!vis[i])dfs(i);
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>u;
        graph[u].pb(i+1);
        graph[i+1].pb(u);
    }
    for(int i=1;i<=n;i++){
        if(!vis[i])
            visId++,dfs(i);
    }
    sort(cnt+1,cnt+visId+1,greater<int>());
    c=cnt[1]+cnt[2];
    c*=c;
    for(int i=3;i<=visId;i++)c+=cnt[i];
    cout<<c;
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second

using namespace std;

const int N=1e6+7;

//scanf("%d",&);
int n,graph[N];
ll c;
bool vis[N];
vector<int> cnt;

int dfs(int x,int c=1){
    vis[x]=1;
    if(!vis[graph[x]])return dfs(graph[x],c+1);
    return c;
}

int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>graph[i];

    for(int i=1;i<=n;i++)
        if(!vis[i])cnt.pb(dfs(i));

    sort(cnt.begin(),cnt.end(),greater<int>());
    c=cnt[0]+cnt[1];
    c*=c;
    for(int i=2;i<cnt.size();i++)c+=cnt[i]*cnt[i];
    cout<<c;
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second

using namespace std;

const int N=1e6+7;

//scanf("%d",&);
int n,graph[N];
ll c;
bool vis[N];
vector<int> cnt;

int dfs(int x,int c=1){
    vis[x]=1;
    if(!vis[graph[x]])return dfs(graph[x],c+1);
    return c;
}

int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>graph[i];

    for(int i=1;i<=n;i++)
        if(!vis[i])cnt.pb(dfs(i));

    sort(cnt.begin(),cnt.end(),greater<int>());
    c=cnt[0]+cnt[1];
    c*=c;
    for(int i=2;i<cnt.size();i++)c+=cnt[i];
    cout<<c;
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second

using namespace std;

const int N=1e6+7;

//scanf("%d",&);
int n,vis[N],visId,u;
ll cnt[N],c;
vector<int> graph[N];

void dfs(int x){
    vis[x]=visId;
    cnt[visId]++;
    for(int i:graph[x])
        if(!vis[i])dfs(i);
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>u;
        graph[i+1].pb(u);
    }
    for(int i=1;i<=n;i++){
        if(!vis[i])
            visId++,dfs(i);
    }
    sort(cnt+1,cnt+visId+1,greater<int>());
    c=cnt[1]+cnt[2];
    c*=c;
    for(int i=3;i<=visId;i++)c+=cnt[i];
    cout<<c;
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second

using namespace std;

const int N=1e6+7;

//scanf("%d",&);
int n,vis[N],visId,u;
ll cnt[N],c;
vector<int> graph[N];

void dfs(int x){
    vis[x]=visId;
    cnt[visId]++;
    for(int i:graph[x])
        if(!vis[i])dfs(i);
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>u;
        graph[u].pb(i+1);
        graph[i+1].pb(u);
    }
    for(int i=1;i<=n;i++){
        if(!vis[i])
            visId++,dfs(i);
    }
    sort(cnt+1,cnt+visId+1,greater<int>());
    c=cnt[1]+cnt[2];
    c*=c;
    for(int i=3;i<=visId;i++)c+=cnt[i];
    cout<<c;
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define mp make_pair
#define ff first
#define ss second

using namespace std;

const int N=1e6+7;

//scanf("%d",&);
int n,u,graph[N];
ll c;
bool vis[N];
vector<int> cnt;

void dfs(int x,int c=1){
    vis[x]=1;
    if(!vis[graph[x]])dfs(graph[x],c+1);
    else cnt.pb(c);
}

int main()
{
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>u;
        graph[i+1]=u;
    }
    for(int i=1;i<=n;i++)
        if(!vis[i])dfs(i);

    sort(cnt.begin(),cnt.end(),greater<int>());
    c=cnt[0]+cnt[1];
    c*=c;
    for(int i=2;i<cnt.size();i++)c+=cnt[i];
    cout<<c;
    return 0;
}


#include <stdio.h>
#include <algorithm>
using namespace std;

bool vis[100001];
int to[100001];
long long group[100001];

int dfs (int cur, int loop)
{
    vis[cur] = 1;
    if (to[cur] == loop) return 1;
    return 1 + dfs(to[cur], loop);
}

int main()
{
    int n;
    scanf("%d", &n);

    for (int i=1 ; i<=n ; i++)
        scanf("%d", &to[i]);

    int sz = 0;
    for (int i=1 ; i<=n ; i++)
        if (!vis[i])
            group[++sz] = dfs(i, i);

    sort(group+1, group+sz+1);
    long long ans = 0;
    if (sz > 1) group[sz-1] += group[sz];
    else ans = group[1] * group[1];

    for (int i=1 ; i<sz ; i++)
        ans += (group[i] * group[i]);
    printf("%I64d\n", ans);

    return 0;
}


#include <stdio.h>
#include <algorithm>
using namespace std;

bool vis[100001];
int to[100001], group[100001];

int dfs (int cur, int loop)
{
    vis[cur] = 1;
    if (to[cur] == loop) return 1;
    return 1 + dfs(to[cur], loop);
}

int main()
{
    int n;
    scanf("%d", &n);

    for (int i=1 ; i<=n ; i++)
        scanf("%d", &to[i]);

    int sz = 0;
    for (int i=1 ; i<=n ; i++)
        if (!vis[i])
            group[++sz] = dfs(i, i);

    sort(group+1, group+sz+1);
    long long ans = 0;
    if (sz > 1) group[sz-1] += group[sz];
    else ans = group[1] * group[1];

    for (int i=1 ; i<sz ; i++)
        ans += (group[i] * group[i]);
    printf("%I64d\n", ans);

    return 0;
}


#include <stdio.h>
#include <algorithm>
using namespace std;

bool vis[100001];
int to[100001], group[100001];

int dfs (int cur, int loop)
{
    vis[cur] = 1;
    if (to[cur] == loop) return 1;
    return 1 + dfs(to[cur], loop);
}

int main()
{
    int n;
    scanf("%d", &n);

    for (int i=1 ; i<=n ; i++)
        scanf("%d", &to[i]);

    int sz = 0;
    for (int i=1 ; i<=n ; i++)
        if (!vis[i])
            group[++sz] = dfs(i, i);

    sort(group+1, group+sz+1);
    long long ans = 0;
    if (sz > 1) group[sz-1] += group[sz];
    else ans = group[1];

    for (int i=1 ; i<sz ; i++)
        ans += (group[i] * group[i]);
    printf("%I64d\n", ans);

    return 0;
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class knight {
    public static void main(String[] args) throws FileNotFoundException {
        int n, i = 0;
        int[] arr;
        File file =
                new File("input.txt");
        Scanner sc = new Scanner(file);
        n = sc.nextInt();
        arr = new int[n];
        while ( i<n) {
            arr[i] = sc.nextInt();
            i++;
        }
        PrintStream o = new PrintStream(new File("output.txt"));
        System.setOut(o);
        for(i =0; i<n; i++ ) {
            if (arr[i] % 2 == 0)
                System.out.println("0");
            else
                System.out.println("1");
        }
    }
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class knight {
    public static void main(String[] args) throws FileNotFoundException {
        int n, i = 0;
        int[] arr;
        File file =
                new File("input.txt");
        Scanner sc = new Scanner(file);
        n = sc.nextInt();
        arr = new int[n];
        while ( i<n) {
            arr[i] = sc.nextInt();
            i++;
        }
        File file1 = new File("output.txt");
        PrintStream stream = new PrintStream(file1);
        System.setOut(stream);
        for(i =0; i<n; i++ ) {
            if (arr[i] % 2 == 0)
                System.out.println("1");
            else
                System.out.println("0");
        }
    }
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class knight {
    public static void main(String[] args) throws FileNotFoundException {
        int n, i = 0;
        int[] arr;
        File file =
                new File("input.txt");
        Scanner sc = new Scanner(file);
        n = sc.nextInt();
        arr = new int[n];
        while ( i<n) {
            arr[i] = sc.nextInt();
            i++;
        }
        File file1 = new File("output.txt");
        PrintStream stream = new PrintStream(file1);
        System.setOut(stream);
        for(i =0; i<n; i++ ) {
            if (arr[i] % 2 == 0)
                System.out.println("0");
            else
                System.out.println("1");
        }
    }
}


import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class lol {
    public static void main(String[] args) throws FileNotFoundException {
        int n;
        Queue<Integer> q = new LinkedList<>();
        File file =
                new File("input.txt");
        Scanner sc = new Scanner(file);
        n = sc.nextInt();
        while (sc.hasNextInt())
            q.add(sc.nextInt());
        PrintStream o = new PrintStream(new File("A.txt"));
        System.setOut(o);
        for( int no : q) {
            if (no % 2 == 0)
                System.out.println("0");
            else
                System.out.println("1");
        }
    }
}


import java.util.*;
import java.io.*;
import java.math.*;

public class Main {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
            try {
                br = new BufferedReader(new FileReader("input.txt"));
            } catch (IOException error) {
            }
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    public static void main(String[] args) {
        FastReader fr = new FastReader();
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileWriter("output.txt"));
        } catch (IOException error) {

        }
        int t = fr.nextInt();
        while (t-- > 0) {
            int n = fr.nextInt();
            if (n % 2 == 1) out.println(0);
            else out.println(1);
        }
        out.flush();
    }
}


import java.util.*;
import java.io.*;
import java.math.*;

public class Main {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    public static void main(String[] args) {
        FastReader fr = new FastReader();
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int t = fr.nextInt();
        while (t-- > 0) {
            int n = fr.nextInt();
            if (n % 2 == 1) System.out.println(0);
            else System.out.println(1);
        }
        out.flush();
    }
}


import java.util.*;
import java.io.*;
import java.math.*;

public class Main {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
            try {
                br = new BufferedReader(new FileReader("input.txt"));
            } catch (IOException error) {
            }
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    public static void main(String[] args) {
        FastReader fr = new FastReader();
        PrintWriter out = null;
        try {
            out = new PrintWriter(new FileWriter("output.txt"));
        } catch (IOException error) {

        }
        int t = fr.nextInt();
        while (t-- > 0) {
            int n = fr.nextInt();
            if (n % 2 == 1) System.out.println(0);
            else System.out.println(1);
        }
        out.flush();
    }
}


import java.util.*;
import java.io.*;
import java.math.*;

public class Main {
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;
        public FastReader() {
            br = new BufferedReader(new FileReader("input.txt"));
        }
        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException  e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
        int nextInt() {
            return Integer.parseInt(next());
        }
        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

    public static void main(String[] args) {
        FastReader fr = new FastReader();
        PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
        int t = fr.nextInt();
        while (t-- > 0) {
            int n = fr.nextInt();
            if (n % 2 == 1) System.out.println(1);
            else System.out.println(0);
        }
        out.flush();
    }
}


#include <set>
#include <map>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <iostream>
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second

using namespace std;
const int INF = 0x3f3f3f3f;//?????
typedef long long ll;
typedef long double ld;
typedef pair<ll, int>  pll;
typedef pair<int, int> pii;
const int N = 1000000;
int a[55],b[55],prime[N],st[N];ll sum[N];
int cnt;
ll qpow(ll x,ll y,ll mod)
{
	int ans=1;
	while(y)
	{
		if(y&1) ans=ans*x%mod;
		x=x*x%mod;
		y>>=1;
	}
	return ans%mod;
}
void ola()
{
	for(int i=2;i<=1000000;i++)
	{
		if(st[i]==0)
		{
			prime[cnt++]=i;
		}
		for(int j=0;j<cnt&&i*prime[j]<=1000000;j++)
		{
			st[i*prime[j]]=1;
			if(i%prime[j]==0) break;
		 }
	}
}
int main()
{
	IOS;
	int t; cin >> t;
	while(t--)
	{
		int n; cin >> n;
		if(n&1) cout << 0 << endl;
		else cout << 1 << endl;
	}
	return 0;
}


#include <set>
#include <map>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <algorithm>
#include <iostream>
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second

using namespace std;
const int INF = 0x3f3f3f3f;//?????
typedef long long ll;
typedef long double ld;
typedef pair<ll, int>  pll;
typedef pair<int, int> pii;
const int N = 1000000;
int a[55],b[55],prime[N],st[N];ll sum[N];
int cnt;
ll qpow(ll x,ll y,ll mod)
{
	int ans=1;
	while(y)
	{
		if(y&1) ans=ans*x%mod;
		x=x*x%mod;
		y>>=1;
	}
	return ans%mod;
}
void ola()
{
	for(int i=2;i<=1000000;i++)
	{
		if(st[i]==0)
		{
			prime[cnt++]=i;
		}
		for(int j=0;j<cnt&&i*prime[j]<=1000000;j++)
		{
			st[i*prime[j]]=1;
			if(i%prime[j]==0) break;
		 }
	}
}
int main()
{
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	IOS;
	int t; cin >> t;
	while(t--)
	{
		int n; cin >> n;
		if(n&1) cout << 0 << endl;
		else cout << 1 << endl;
	}
	return 0;
}


#include <bits/stdc++.h>

using namespace std ;

int main(){
	int t ;
	cin >> t ;
	while (t--){
		int n ;
		cin >> n ;
		cout << abs((n % 2) - 1) << endl ;
	}
	return 0 ;
}


#include <bits/stdc++.h>

using namespace std ;

int main(){
	freopen("input.txt" ,"r" ,stdin) ;
	freopen("output.txt" ,"w" ,stdout) ;
	int t ;
	cin >> t ;
	for (int i=0 ; i<t ; i++){
		int n ;
		cin >> n ;
		cout << abs((n % 2) - 1) << endl ;
	}
	return 0 ;
}


#include <bits/stdc++.h>

using namespace std ;

int main(){
	int t ;
	cin >> t ;
	for (int i=0 ; i<t ; i++){
		int n ;
		cin >> n ;
		cout << abs((n % 2) - 1) << endl ;
	}
	return 0 ;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef long double ldb;
#define en "\n"
#define st string
#define pb push_back
#define eb emplace_back
#define frep freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);

void solve(){
    int n; cin >> n; if(n&1) cout << 0 << en; else cout << 1 << en;
}

int main(){
    fastio
    frep
    int t; cin >> t; while(t--) solve();
    //solve();
    return 0;
}