The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.

There are n stations in the subway. It was built according to the Bertown Transport Law:

  For each station i there exists exactly one train that goes from this station. Its destination station is p_{i}, possibly p_{i} = i;  For each station i there exists exactly one station j such that p_{j} = i. 

The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).

The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of p_{i} for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.

The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get! 


-----Input-----

The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.

The second line contains n integer numbers p_1, p_2, ..., p_{n} (1 ≤ p_{i} ≤ n) — the current structure of the subway. All these numbers are distinct.


-----Output-----

Print one number — the maximum possible value of convenience.


-----Examples-----
Input
3
2 1 3

Output
9

Input
5
1 5 4 3 2

Output
17



-----Note-----

In the first example the mayor can change p_2 to 3 and p_3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).

In the second example the mayor can change p_2 to 4 and p_3 to 5.

Difficulty: interview

Starter code:

Solutions:
n = int(input())
p = list(map(int, input().split()))

ls = []
visited = [False for _ in range(n)]
cnt = 0
for i in range(n):
    j = i
    cnt = 0
    while not visited[j]:
        visited[j] = True
        cnt += 1
        j = p[j] - 1
    if 0 < cnt:
        ls.append(cnt)

ls.sort()
if 1 < len(ls):
    ls[-2] += ls[-1]
    ls.pop()

print(sum([x**2 for x in ls]))



# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 19:33:34 2017

@author: savit
"""

n=int(input())
a=list(map(int,input().split()))
b=[]
chains=[]
for i in range(n):
    b.append(True)
for i in range(n):
    if(b[i]):
        chains.append([i,])
        j=i
        b[j]=False
        while((a[j]-1)!=chains[-1][0]):
            
            chains[-1].append(a[j]-1)
            
            j=a[j]-1
            b[j]=False
chainlen=list(map(len,chains))
if(len(chains)>1):
    #print("entered")
    
    max1=max(chainlen)
    max1=chainlen.index(max1)
    chainlen[max1]*=-1
    
    max2=max(chainlen)
    max2=chainlen.index(max2)
    #print(max1,max2,chainlen)
    chainlen[max2]=chainlen[max2]+(-1*chainlen[max1])
    del chainlen[max1]
con=0
#print(chains)
#print(chainlen)
for i in chainlen:
    con+=i*i
print(con)        


n = int(input())
p = list(map(int,input().split()))
vis = [False]*n
nv = 0
m = 0
cyc = []
while nv<n:
    while vis[m]:
        m+=1
    temp = []
    c = m
    while not vis[c]:
        temp.append(c)
        nv += 1
        vis[c] = True
        c = p[c]-1
    cyc.append(temp)
size = []
for i in range(len(cyc)):
    size.append(len(cyc[i]))
size = sorted(size)
if len(size)==1:
    print(size[0]*size[0])
else:
    out = (size[len(size)-1]+size[len(size)-2])*(size[len(size)-1]+size[len(size)-2])
    for i in range(len(size)-2):
        out += size[i]*size[i]
    print(out)



n = int(input())
data = list(map(int,input().split()))

gp = { i:i for i in range(n) }
sets = { i:[i] for i in range(n) }

for i in range(n):
    u,v = i,data[i]-1
    if gp[u]!= gp[v]:
        temp=gp[v]
        for i in sets[gp[v]]:
            gp[i]=gp[u]
            sets[gp[u]].append(i)
        del sets[temp]

l=[]
for i in sets:
    l.append(len(sets[i]))
l.sort(reverse=True)
n=len(l)
if n==1:
    print(l[0]*l[0])
else:
    ans=(l[0]+l[1])**2
    for i in range(2,n):
        ans+=l[i]**2
    print(ans)


r = lambda: map(int, input().split())

def main():
	n, = r()
	p = [x - 1 for x in r()]
	vis = [False] * n
	lens = []
	for i in range(n):
		if vis[i]:
			continue
		vis[i], cc = True, 1
		j = p[i]
		while not vis[j]:
			vis[j] = True
			cc += 1
			j = p[j]
		lens.append(cc)
	lens.sort()
	if len(lens) > 1:
		lens[-2] += lens[-1]
		lens.pop()
	print(sum(x * x for x in lens))

main()

n=int(input())
p=[0]*(n+1)
p[1:n+1]=list(map(int,input().split()))
c=[]
used=[False]*(n+1)
for i in range(1,n+1):
    if used[i]:
        continue
    s=list()
    s.append(i)
    used[i]=True
    j=p[i]
    while not used[j]:
        s.append(j)
        used[j]=True
        j=p[j]
    c.append(len(s))
if len(c)==1:
    print(n*n)
else:
    c.sort()
    c.reverse()
    #print(c)
    m=c[0]+c[1]
    print(m*m+sum([d*d for d in c[2:]]))




n = int(input())
ps = list(map(lambda x: int(x)-1, input().split()))

sum = 0
maxest_pipe = 0
max_pipe = 0

free_points = set(range(n))
free_points.remove(0)
start_point = 0
current_point = 0
steps = 0
while True:
    steps += 1
    next_point = ps[current_point]
    if next_point in free_points:
        free_points.remove(next_point)
    if next_point == start_point:

        sum += steps * steps
        if steps > maxest_pipe:
            max_pipe = maxest_pipe
            maxest_pipe = steps
        elif steps > max_pipe:
            max_pipe = steps
        steps = 0
        if len(free_points) > 0:
            current_point = free_points.pop()
            start_point = current_point
        else:
            break
    else:
        current_point = next_point

print(sum - max_pipe*max_pipe - maxest_pipe*maxest_pipe + (max_pipe+maxest_pipe)*(max_pipe+maxest_pipe))

n = int(input())
inp= input()
inp = inp.split()
for i in range(n):
    inp[i] = int(inp[i])
vis = [0 for i in range(n)]
siz = []
for i in range(n):
    if vis[i]==1:
        continue
    vis[i] = 1
    j=inp[i]-1
    count = 1
    while vis[j]!=1:
        count+=1
        vis[j]=1
        j = inp[j]-1
    siz.append(count)
siz.sort(reverse = True)
if len(siz)==1:
    print(siz[0]**2)
else:
    ans = (siz[0]+siz[1])**2
    for i in range(2, len(siz)):
        ans+= siz[i]*siz[i]
    print(ans)


n = int(input())
p = list(map(int, input().split()))

used = [False] * n
nums = list()


def count(i):
    c = 0
    while True:
        if used[i]:
            return c
        else:
            used[i] = True
            i = p[i] - 1
            c += 1


for i in range(n):
    if not used[i]:
        nums.append(count(i))

if n == 1:
    print(1)
elif n == 2:
    print(4)
else:
    nums.sort(reverse=True)
    if len(nums) > 1:
        c = (nums[0] + nums[1]) ** 2
        for i in nums[2:]:
            c += i ** 2
        print(c)
    else:
        print(nums[0] ** 2)


n = int(input())
p = list(map(int, input().split()))

used = [False] * n
nums = list()


def count(i):
    c = 0
    while True:
        if used[i]:
            return c
        else:
            used[i] = True
            i = p[i] - 1
            c += 1


for i in range(n):
    if not used[i]:
        nums.append(count(i))

if n == 1:
    print(1)
elif n == 2:
    print(4)
else:
    nums.sort(reverse=True)
    if len(nums) > 1:
        c = (nums[0] + nums[1]) ** 2
        for i in nums[2:]:
            c += i ** 2
        print(c)
    else:
        print(nums[0] ** 2)


from collections import defaultdict as dd
g=dd(list)
def addE(u,v):
	g[u].append(v)
	g[v].append(u)
n=int(input())
l=[int(x) for x in input().split()]
for i in range(n):
	addE(i+1,l[i])
visited=[False]*(n+1)
def dfs(v,count):
	visited[v]=True
	stack=[v]
	while len(stack)!=0:
		cur=stack.pop()
		for ch in g[cur]:
			if visited[ch]:
				continue
			visited[ch]=True
			count+=1
			stack.append(ch)
	return count

ans=[]
for i in range(1,n+1):
	if not visited[i]:
		ans.append(dfs(i,1))

ans=sorted(ans,reverse=True)
if  len(ans) ==1:
	print(ans[0]*ans[0])
else:
	ans[1]+=ans[0]
	ans.pop(0)
	print(sum(x*x for x in ans))





#!/usr/bin/env python3

n = int(input())
P = [int(p)-1 for p in input().split()]  # permutation
seen = [False]*n
res = m0 = m1 = 0
for i in range(n):
    if not seen[i]:
        seen[i] = True
        j = P[i]
        c = 1  # taille du cycle
        while j!=i:
            seen[j] = True
            j = P[j]
            c += 1
        res += c*c
        if c>m0:
            m0,m1 = c,m0
        elif c>m1:
            m1 = c
# on fusionne les 2 plus grands cycles
res += (m0+m1)*(m0+m1)-m0*m0-m1*m1
print(res)


n = int(input())
p = [int(x)-1 for x in input().split()]
encontrados = [False]*n
ciclos = []
for i in range(n):
	if encontrados[i]:
		continue
	ciclos.append([i])
	encontrados[i] = True
	j = p[i]
	while not encontrados[j]:
		ciclos[-1].append(j)
		encontrados[j] = True
		j = p[j]
primero = max([len(x) for x in ciclos])
for i in range(n):
	if len(ciclos[i]) == primero:
		ciclos.pop(i)
		break
if ciclos:
	segundo = max([len(x) for x in ciclos])
else:
	segundo = 0
print((primero+segundo)**2 + sum([len(x)**2 for x in ciclos]) - segundo**2)


n = int(input())
p = list(map(int, input().split(" ")))
ls = []
vis = [False for i in range(n)]
cnt = 0
for i in range(n):
    j = i
    cnt = 0
    while not(vis[j]):
        vis[j] = True
        cnt += 1
        j = p[j] - 1
    if cnt>0:
        ls.append(cnt)
ls.sort()
if len(ls)>1:
    ls[-2] += ls[-1]
    ls.pop()
ans=0
for i in ls:
    ans=ans+i**2
print(ans)


n = int(input())
edges = [int(x) - 1 for x in input().split()]
visited = [False for _ in range(n)]

sizes = []
for i in range(n):
    if visited[i]:
        continue
    visited[i] = True
    component_size = 1

    j = edges[i]
    while not visited[j]:
        visited[j] = True
        component_size += 1
        j = edges[j]

    sizes.append(component_size)

sizes = sorted(sizes)
if len(sizes) > 1:
    sizes[-2] += sizes[-1]
    sizes.pop()

print(sum([x**2 for x in sizes]))


n = int(input())
p = [0] + list(map(int, input().split()))

def visit(v):
  res = 0
  while p[v] != 0:
    res += 1
    x = p[v]
    (p[v], v) = (0, x)    
  return res 

val = sorted([visit(v) for v in range(n + 1)])
print(sum(list([x*x for x in val])) + 2 * val[-1] * val[-2])


n=int(input())
p=[int(x) for x in input().split()]
p.insert(0,-3)
max1,max2=0,0
used=[0]*(n+1)
count=0
for i in range (1, n+1):
    m=0
    v=i
    while used[p[v]]==0:
        used[p[v]]=1
        v=p[v]
        m+=1
    if m>max2:
        max2=m
    if max2>max1:
        max2,max1=max1,max2
    count+=m**2
count=count-max1**2-max2**2+(max1+max2)**2

print(count)

# http://codeforces.com/contest/884/problem/C
# unsolved
from functools import lru_cache

n = int(input())
p = list(map(int, input().split()))

l = []
score = 0
jeden = 0
dwa = 0


@lru_cache(maxsize=10000)
def wzor(s):
    return s * s


for i in range(n):

    if p[i] != 0:
        start = i
        end = p[i]
        lenght = 0
        k = 0

        if start + 1 != p[i]:

            while k - 1 != start:
                k = end
                end = p[end - 1]
                p[k - 1] = 0
                lenght += 1

        else:
            p[end - 1] = 0
            lenght += 1

        if lenght > jeden:
            l.append(dwa)
            dwa = jeden
            jeden = lenght

        elif lenght > dwa:
            l.append(dwa)
            dwa = lenght

        else:
            l.append(lenght)

        length = 0

l.append(jeden + dwa)

for iteam in l:
    if iteam != 1 or iteam != 0 :
        score += wzor(iteam)
    elif iteam == 1:
        score += 1

print(int(score))

n = int(input())
a = list(map(int, input().split()))
vis = [False] * 100005
b = []
m = 0
for i in range(n):
    if not vis[i]:
        m += 1
        cur = i
        len = 0
        while not vis[cur]:
            vis[cur] = True
            len += 1
            cur = a[cur] - 1
        b.append(len)
b.sort()
if m > 1:
    b[-2] += b[-1]
    b.pop()
print(sum(map(lambda x : x**2, b)))

n = int(input())
p = [0] + list(map(int, input().split()))

def visit(v):
  res = 0
  while p[v] != 0:
    res += 1
    x = p[v]
    (p[v], v) = (0, x)    
  return res 

val = sorted([visit(v) for v in range(n + 1)])
print(sum(list(map(lambda x: x*x, val))) + 2 * val[-1] * val[-2])


bz=[0 for i in range(1000000)]
to=[0 for i in range(1000000)]
n=0
n=int(input())
i=1
for x in (input().split()):
	to[i]=int(x)
	i+=1
all_num=0
mx1=0
mx2=0
for i in range(1,n+1):
	if (bz[i]==0):
		x=i
		num=0;
		while (bz[x]==0):
			num+=1
			bz[x]=1
			x=to[x]
		all_num+=num**2
		if (mx1<=num):
			mx1,mx2=num,mx1
		elif mx2<num:
			mx2=num

print(all_num-(mx1**2)-(mx2**2)+((mx1+mx2)**2))
			


n=int(input())
a=list(map(int,input().split()))
b=[0]*n
k1=0
s=[]
for i in range (n):
    if b[i]==0:
        j=a[i]-1
        k=1
        b[i]=1
        sp=[i]
        while b[j] == 0:
            sp.append(j)
            k+=1
            j=a[j]-1
        s.append(min(k1,k))
        k1=max(k1,k)
        for u in sp:
            b[u]=k
#print(s,b,k1)
k2=max(s)
print(sum(list([x*x for x in s]))+k1*k1 + 2*k1*k2)


n = int(input())
p = list(map(int, input().split()))
p = [i - 1 for i in p]
vis = [False for _ in range(n)]

sz = [0]

for i in range(n):
    j = i
    cnt = 0
    while not vis[j]:
        vis[j] = True
        cnt += 1
        j = p[j]
    if 0 < cnt:
        sz.append(cnt)

sz.sort()
print(sum(list(map(lambda x: x*x, sz))) + 2 * sz[-1] * sz[-2])

n = int(input())
p = list(map(int, input().split()))
p = [i - 1 for i in p]
vis = [False for _ in range(n)]

sz = [0]


def dfs(v):
    cnt = 0
    while not vis[v]:
        vis[v] = True
        cnt += 1
        v = p[v]
    return cnt

for i in range(n):
    cnt = dfs(i)
    if cnt > 0:
        sz.append(cnt)

sz.sort()
print(sum(list(map(lambda x: x*x, sz))) + 2 * sz[-1] * sz[-2])

class node:
    def __init__(self,index):
        self.index = index
        self.nextN = None
        self.visited = 0
        # 0 - not visited
        # 1 - visited


n = int(input())
nodes = [node(i+1) for i in range(n)]
c = [int(i) for i in input().split()]
i = 0
while i<n:
    nodes[i].nextN = nodes[c[i]-1]
    i+=1
    
sequence = []

i = 0
news = []
while i<n:
    x = i
    while(nodes[x].visited!=1):
        news.append(nodes[x])
        nodes[x].visited = 1
        x = nodes[x].nextN.index - 1
    sequence.append(news)
    news=[]
    i+=1
sequence.sort(key=len,reverse=True)
if(n==1):
    print(1)
elif(n==2):
    print(4)
else:
    x = len(sequence[0])+len(sequence[1])
    x *=x
    som = 0
    for i in range(2,n):
        value = len(sequence[i])
        if(value == 0):
            break
        som+=value*value
    print(x+som)