๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 6118 - ์ˆจ๋ฐ”๊ผญ์งˆ

by HandHand 2021. 6. 7.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 6118๋ฒˆ

ํ’€์ด ๊ณผ์ •

์‹œ์ž‘ ์ •์ ์—์„œ ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ ์ค‘ ๊ฐ€์žฅ ๊ธด ๊ฒฝ๋กœ๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ํ™œ์šฉํ•˜์—ฌ ํ•œ ์ •์ ์œผ๋กœ๋ถ€ํ„ฐ ๋‹ค๋ฅธ ๋ชจ๋“  ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•œ ๋‹ค์Œ,
๊ฐ€์žฅ ๊ฑฐ๋ฆฌ๊ฐ€ ๋จผ ์ •์ ์„ ์ฐพ์•„์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ด๋•Œ ๊ตฌํ˜„์˜ ํŽธ์˜๋ฅผ ์œ„ํ•ด์„œ dist ๋ฐฐ์—ด์„ ๊ฑฐ๋ฆฌ๊ฐ’๊ณผ ์ •์  ๋ฒˆํ˜ธ์ˆœ์œผ๋กœ ์ •๋ ฌํ•˜์—ฌ ๋‹ต์„ ๊ตฌํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
import heapq


INF = sys.maxsize
N, M = list(map(int, sys.stdin.readline().split()))
adj = [[] for _ in range(N+1)]
for _ in range(M):
    frm, to = list(map(int, sys.stdin.readline().split()))
    adj[frm].append(to)
    adj[to].append(frm)


def dijkstra():
    pq = []
    dist = [INF for _ in range(N+1)]

    dist[1] = 0
    heapq.heappush(pq, (0, 1))

    while pq:
        cost, here = heapq.heappop(pq)

        if dist[here] < cost:
            continue

        for there in adj[here]:
            next = cost + 1  # ๊ฐ ์ •์  ์‚ฌ์ด์˜ ๊ฐ€์ค‘์น˜๋Š” 1์ด๋‹ค.
            if next < dist[there]:
                dist[there] = next
                heapq.heappush(pq, (next, there))

    # ํ—›๊ฐ„ ๊ฐ€์žฅ ๋จผ ๊ฒƒ์„ ์ฐพ๋Š”๋‹ค.
    temp = list(zip(dist[1:], range(1, len(dist))))
    temp = sorted(temp, key=lambda x: (-x[0], x[1]))

    # ๊ฑฐ๋ฆฌ๊ฐ€ ๊ฐ™์€ ํ—›๊ฐ„ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค.
    same = 1
    for d, _ in temp[1:]:
        if d == temp[0][0]:
            same += 1

    return [temp[0][1], temp[0][0], same]


def solution():
    ans = dijkstra()
    return ' '.join(map(str, ans))


print(solution())
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 15684 - ์‚ฌ๋‹ค๋ฆฌ ์กฐ์ž‘  (0) 2021.06.07
BOJ 1781 - ์ปต๋ผ๋ฉด  (0) 2021.06.07
BOJ 2331 - ๋ฐ˜๋ณต์ˆ˜์—ด  (0) 2021.06.07
BOJ 4889 - ์•ˆ์ •์ ์ธ ๋ฌธ์ž์—ด  (0) 2021.06.07
BOJ 4811 - ์•Œ์•ฝ  (0) 2021.06.07

๐Ÿ’ฌ ๋Œ“๊ธ€