Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/PythonํŒŒ์ด์ฌ] ๋ชจ๋‘ 0์œผ๋กœ ๋งŒ๋“ค๊ธฐ

meeeeejin 2021. 5. 21. 10:38

๋ฌธ์ œ ์ถœ์ฒ˜: https://programmers.co.kr/learn/courses/30/lessons/76503

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋ชจ๋‘ 0์œผ๋กœ ๋งŒ๋“ค๊ธฐ

๊ฐ ์ ์— ๊ฐ€์ค‘์น˜๊ฐ€ ๋ถ€์—ฌ๋œ ํŠธ๋ฆฌ๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ๋‹น์‹ ์€ ๋‹ค์Œ ์—ฐ์‚ฐ์„ ํ†ตํ•˜์—ฌ, ์ด ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ์ ๋“ค์˜ ๊ฐ€์ค‘์น˜๋ฅผ 0์œผ๋กœ ๋งŒ๋“ค๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค. ์ž„์˜์˜ ์—ฐ๊ฒฐ๋œ ๋‘ ์ ์„ ๊ณจ๋ผ์„œ ํ•œ์ชฝ์€ 1 ์ฆ๊ฐ€์‹œํ‚ค๊ณ , ๋‹ค๋ฅธ ํ•œ

programmers.co.kr

 

 

๋ฌธ์ œ ์„ค๋ช…

DFS๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•œ๋‹ค๋Š” ์•„์ด๋””์–ด๊ฐ€ ์•ˆ ๋– ์˜ฌ๋ผ์„œ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋‚ฌ๋˜ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. ์ •์ ์„ ๋ชจ๋‘ ๋ฐฉ๋ฌธํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ DFS๊ฐ€ ์™œ ์•ˆ ๋– ์˜ฌ๋ž์„๊นŒ์š”? ์ €๋Š” ๋ฐ”๋ณด์ž…๋‹ˆ๋‹ค. 

 

๋งŒ์•ฝ ๋ฆฌ์ŠคํŠธ a์˜ ์›์†Œ์˜ ํ•ฉ์ด 0์ด ๋˜์ง€ ์•Š๋Š”๋‹ค๋ฉด, ์ฃผ์–ด์ง„ ์—ฐ์‚ฐ์„ ํ†ตํ•ด ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๊ฐ€์ค‘์น˜๋ฅผ 0์œผ๋กœ ๋งŒ๋“ค ์ˆ˜ ์—†์œผ๋ฏ€๋กœ -1์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. 

 

DFS๋ฅผ ์ด์šฉํ•ด์„œ ์ •์ ์„ ํƒ์ƒ‰ํ•˜๋Š”๋ฐ, ์ œ์ผ ๋ ์ •์ (์—ฐ๊ฒฐ๋œ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ •์ ์ด ์—†๋Š” ๊ฒฝ์šฐ)๋ถ€ํ„ฐ 0์œผ๋กœ ๋งŒ๋“ค์–ด์ค๋‹ˆ๋‹ค. 0์œผ๋กœ ๋งŒ๋“ค์–ด์ค€๋‹ค๋Š” ๊ฒƒ์€ ๊ฒฐ๊ตญ ์ž์‹ ์„ dfs๋กœ ํ˜ธ์ถœํ•œ ๋ถ€๋ชจ ์ •์ ์— ์ž์‹ ์˜ ๊ฐ€์ค‘์น˜๋ฅผ ๋”ํ•˜๋Š” ๊ฒƒ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค. ํ˜„์žฌ ์ •์ ์„ 0์œผ๋กœ ๋งŒ๋“ค๊ธฐ ์œ„ํ•œ ์—ฐ์‚ฐ์˜ ํšŸ์ˆ˜๋Š” ์ •์ ์˜ ๊ฐ€์ค‘์น˜์˜ ์ ˆ๋Œ€๊ฐ’์ž…๋‹ˆ๋‹ค. 

 

 

์†Œ์Šค์ฝ”๋“œ

import sys
sys.setrecursionlimit(300000)
from collections import defaultdict
answer = 0

def dfs(x, a, tree, visited):
    global answer
    visited[x] = 1

    for y in tree[x]:
        if not visited[y]:
            visited[y]
            a[x] += dfs(y, a, tree, visited)
    answer += abs(a[x])

    return a[x]


def solution(a, edges):
    global answer

    if sum(a) != 0:
        return -1

    tree = defaultdict(list)
    for i, j in edges:
        tree[i].append(j)
        tree[j].append(i)

    visited = [0]*(len(a))

    dfs(0, a, tree, visited)

    return answer

 

 

 

 

728x90