[TIL_Carrotww] 49 - 22/11/10

μœ ν˜•μ„Β·2022λ…„ 11μ›” 14일
0

TIL

λͺ©λ‘ 보기
59/138
post-thumbnail

πŸ“Carrotww의 μ½”λ”© 기둝μž₯

🧲 python algorithm

πŸ” programmers λ“±λŒ€
ν”„λ‘œμ νŠΈ λλ‚˜κ³  μ €λ²ˆμ— λͺ» ν’€μ—ˆλ˜ 문제 풀어보렀고 ν•˜λŠ”λ° 두 가지 λ°©λ²•μœΌλ‘œ μ ‘κ·Όν–ˆλŠ”λ° μ•ˆν’€λ¦°λ‹€...
μ°Ύμ•„λ΄€λ”λ‹ˆ μ–΄λ €μš΄ λ¬Έμ œκΈ°λŠ” ν•˜λ”λΌ (μΉœκ΅¬κ°€ κ³¨λžλŠ”λ° μ…‹ λ‹€ λͺ»ν’€μ •λ„μ˜ 파멸적인 λ‚œμ΄λ„)
일단 두 방법 λͺ¨λ‘ 기둝해 보렀고 ν•œλ‹€ γ… 
λͺ»ν’€μ—ˆμ§€λ§Œ...

  • 1번 풀이
from collections import defaultdict

def solution(n, lighthouse):
    path_dict = defaultdict(list)
    for a, b in lighthouse:
        path_dict[a].append(b)
        path_dict[b].append(a)

    path_list = sorted(path_dict.items(), key=lambda x:len(x[1]))

    path_list = [[x[0], x[1], len(x[1])] for x in path_list]

    cnt = 0

    while path_list:
        pop_n, pop_path, pop_cnt = path_list.pop()
        cnt += 1
        for x in range(len(path_list)):
            if path_list[x][2] != 0 and pop_n in path_list[x][1]:
                path_list[x][2] -= 1

        if sum([x[2] for x in path_list]) == 0:
            break

        path_list.sort(key=lambda x:x[2])

    return cnt


μœ„ 사진과 같이 각 λ…Έλ“œμ—μ„œ λ§Žμ€ κΈ°μ€€μœΌλ‘œ 정렬을 ν•˜λ©΄
빨간색 뢀뢄이 κ°€μž₯ λ¨Όμ € 빠지고, κ·Έ λ‹€μŒ λ…Έλ“œλ“€μ„ μ •λ ¬,
νŒŒλž€μƒ‰ -> 검정색 순으둜 빠지며 κ·Έ 횟수λ₯Ό return ν•œλ‹€.
ν•˜μ§€λ§Œ μ½”λ“œλ‘œ κ΅¬ν˜„ν•˜λ©΄ sortλ₯Ό κ²Œμ† ν•΄μ£Όκ²Œ 되고 μ‹œκ°„ λ³΅μž‘λ„μ—μ„œ νƒˆλ½ν•œλ‹€. λ¬Όλ‘  μ½”λ“œλ„ μ§€κΈˆ μ™„λ²½νžˆ κ΅¬ν˜„ν•œ 것은 μ•„λ‹ˆλ‹€...

  • 2번 풀이
from collections import defaultdict, deque

def solution(n, lighthouse):
    # start pointλ₯Ό μž‘λŠ”λ‹€ - 맨 끝에 μžˆλŠ” λ…Έλ“œ
    path = defaultdict(list)
    for a, b in lighthouse:
        path[a].append(b)
        path[b].append(a)

    light_list, visited = set(), set()

    start = -1
    for key, val in path.items():
        if len(val) == 1:
            start = key
            light_list.add(val[0])
            break

    queue = deque([start])

    while queue:
        temp = queue.popleft()
        visited.add(temp)
        state = True
        for i in path[temp]:
            if i in light_list:
                state = False
        for i in path[temp]:
            if i in visited:
                continue
            queue.append(i)
        if state and temp not in light_list:
            light_list.add(temp)

    return light_list

BFS λ₯Ό μƒκ°ν•˜μ—¬ μ–‘ μ˜† λ…Έλ“œκ°€ λ°©λ¬Έ ν–ˆλŠ”μ§€λ₯Ό 체크, μ–‘ μ˜† λ…Έλ“œκ°€ 뢈이 μΌœμ ΈμžˆλŠ”μ§€λ₯Ό μ²΄ν¬ν•˜λ©° λΆˆμ„ 킨닀.
λ‹Ήμ—°νžˆ μ•ˆλœλ‹€. ν…ŒμŠ€νŠΈμΌ€μ΄μŠ€ 1μ—μ„œ λΆ™μ–΄μžˆλŠ” λ…Έλ“œκ°€ 뢈이 켜져있기 λ•Œλ¬Έ... μ—¬λŸ¬κ°€μ§€λ₯Ό 해보렀닀가 λͺ»ν’€μ—ˆλ‹€.

  • μž‘λ‹΄
    BFS둜 ν‘ΈλŠ”κ²ƒμ΄ λ§žλŠ” 것 κ°™κΈ°λŠ” ν•œλ° 아직 아이디어λ₯Ό 찾지 λͺ»ν–ˆλ‹€... μ •λ‹΅μžκ°€ 71λͺ…이라 검색해도 λ‚˜μ˜€μ§€ μ•ŠλŠ”κ²ƒμ΄ λ‹΅λ‹΅ν•˜λ‹€..
    내일 λ‹€μ‹œ 풀어봐야겠닀.
profile
Carrot_hyeong

0개의 λŒ“κΈ€