"""Solution code for "BOJ 27117. 위문공연".
- Problem link: https://www.acmicpc.net/problem/27117
- Solution link: http://www.teferi.net/ps/problems/boj/27117
Tags: [math]
"""
def main():
N = int(input())
t = [int(x) - 1 for x in input().split()] # pylint: disable=unused-variable
cycle_sizes = []
visited = [False] * N
for i, visited_i in enumerate(visited):
if visited_i:
continue
cur = i
size = 1
while (cur := t[cur]) != i:
visited[cur] = True
size += 1
cycle_sizes.append(size)
cycle_count = len(cycle_sizes)
same_cycle_exchange = sum(s * (s - 1) // 2 for s in cycle_sizes)
different_cycle_exchange = N * (N - 1) // 2 - same_cycle_exchange
answer = (N * 3 - 2 * (cycle_count + 1)) * same_cycle_exchange
answer += (N * 3 - 2 * (cycle_count - 1)) * different_cycle_exchange
print(answer)
if __name__ == '__main__':
main()