사용자 도구

사이트 도구


ps:problems:boj:24921

Interesting Outing

ps
링크acmicpc.net/…
출처BOJ
문제 번호24921
문제명Interesting Outing
레벨골드 3
분류

트리의 지름

시간복잡도O(t*n)
인풋사이즈t<=100, n<=1000
사용한 언어Python 3.13
제출기록36144KB / 256ms
최고기록256ms
해결날짜2025/11/03

풀이

  • 시작점과 끝점을 고정해놓고서 투어를 시작한다고 해보자. 최적 경로로 움직이면, u→v 단순경로상의 엣지들은 한번씩, 나머지 엣지들은 두번씩 방문하게 된다는 것을 쉽게 알수 있다. 따라서 전체 비용은 {모든 엣지의 비용}*2-{u→v 경로의 비용} 이 되고, u→v 경로의 비용을 가장 크게 하는 u,v를 잡을때 최소 비용을 얻을수 있다. 이것은 결국 트리의 지름을 구하라는 것과 동일하다.
  • 트리의 지름은 O(n)에 구할수 있으므로, 전체 시간복잡도도 O(n)이다

코드

"""Solution code for "BOJ 24921. Interesting Outing".

- Problem link: https://www.acmicpc.net/problem/24921
- Solution link: http://www.teferi.net/ps/problems/boj/24921

Tags: [diameter of tree]
"""

from teflib import psutils
from teflib import wtree as twtree


@psutils.gcj_style
def main():
    _, wtree = twtree.create_wtree_from_input()

    answer = (
        sum(w for u, v, w in twtree.edge_iter(wtree)) * 2
        - twtree.DistanceMeasures(wtree).diameter
    )
    print(answer)


if __name__ == '__main__':
    main()

토론

댓글을 입력하세요:
I X᠎ Q W T
 
ps/problems/boj/24921.txt · 마지막으로 수정됨: 2025/11/03 02:23 저자 teferi