๊ด€๋ฆฌ ๋ฉ”๋‰ด

๐‘†๐‘ข๐‘›๐‘ โ„Ž๐‘–๐‘›๐‘’ ๐‘Ž๐‘“๐‘ก๐‘’๐‘Ÿ ๐‘Ÿ๐‘Ž๐‘–๐‘›โœง

[Python] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์˜์–ด ๋๋ง์ž‡๊ธฐ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฐฐ๋‹ฌ ๋ณธ๋ฌธ

๐—ฃ๐—ฟ๐—ผ๐—ด๐—ฟ๐—ฎ๐—บ๐—บ๐—ถ๐—ป๐—ด๐Ÿ’ป/[๐๐ฒ๐ญ๐ก๐จ๐ง] ๐€๐ฅ๐ ๐จ๐ซ๐ข๐ญ๐ก๐ฆ

[Python] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์˜์–ด ๋๋ง์ž‡๊ธฐ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฐฐ๋‹ฌ

๐ŸคRyusun๐Ÿค 2023. 9. 5. 11:30
#ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์˜์–ด ๋๋ง์ž‡๊ธฐ

def solution(n, words):
    i = 0
    memo = set()
    cnt = 1
    while True:
        if i == len(words):
            return [0,0]
        elif words[i] in memo :
            return [i%n+1, cnt]
        elif i != 0 and words[i][0] != words[i-1][-1]:
            return [i % n + 1, cnt]
        if i%n == n-1:
            cnt += 1
        memo.add(words[i])
        i += 1

 

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฐฐ๋‹ฌ 

import heapq
def solution(N, road, K):
    graph = [[] for _ in range(N+1)]
    for i in range(len(road)):
        a,b,c = road[i]
        graph[a].append([b,c])
        graph[b].append([a,c])
    min_dist = [1e9] * (N+1)
    return dijkstra(graph, min_dist, K)

def dijkstra(graph, min_dist, K):
    queue = []
    heapq.heappush(queue, [0, 1])
    min_dist[1] = 0

    while queue:
        dist, node = heapq.heappop(queue)
        if min_dist[node] > dist:
            min_dist[node] = dist
        for next_node, weight in graph[node]:
            cost = min_dist[node] + weight
            if cost < min_dist[next_node]:
                min_dist[next_node] = cost
                heapq.heappush(queue, [cost, next_node])
    cnt = 0
    for i in min_dist:
        if i <= K:
            cnt += 1

    return cnt