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