목차

위문공연

ps
링크acmicpc.net/…
출처BOJ
문제 번호27117
문제명위문공연
레벨플래티넘 4
시간복잡도O(n)
인풋사이즈n<=100,000
사용한 언어Python 3.11
제출기록42172KB / 88ms
최고기록88ms
해결날짜2023/08/01

풀이

코드

"""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()