```go
package main
import (
"bufio"
"fmt"
"os"
"sort"
)
type FastScanner struct {
r *bufio.Reader
}
func NewFastScanner() *FastScanner {
return &FastScanner{r: bufio.NewReaderSize(os.Stdin, 1<<20)}
}
func (fs *FastScanner) NextInt() int {
sign, val := 1, 0
c, _ := fs.r.ReadByte()
for (c < '0' || c > '9') && c != '-' {
c, _ = fs.r.ReadByte()
}
if c == '-' {
sign = -1
c, _ = fs.r.ReadByte()
}
for c >= '0' && c <= '9' {
val = val*10 + int(c-'0')
c, _ = fs.r.ReadByte()
}
fs.r.UnreadByte()
return sign * val
}
func main() {
in := NewFastScanner()
n := in.NextInt()
p := make([]int, n+1)
for i := 1; i <= n; i++ {
p[i] = in.NextInt()
}
vis := make([]bool, n+1)
var cycles []int64
for i := 1; i <= n; i++ {
if !vis[i] {
cnt := int64(0)
x := i
for !vis[x] {
vis[x] = true
cnt++
x = p[x]
}
cycles = append(cycles, cnt)
}
}
var ans int64
for _, v := range cycles {
ans += v * v
}
if len(cycles) >= 2 {
sort.Slice(cycles, func(i, j int) bool {
return cycles[i] > cycles[j]
})
a, b := cycles[0], cycles[1]
ans = ans - a*a - b*b + (a+b)*(a+b)
}
fmt.Print(ans)
}
```