파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2023. 1. 15. 23:45

https://leetcode.com/problems/number-of-good-paths/

 

Number of Good Paths - LeetCode

Number of Good Paths - There is a tree (i.e. a connected, undirected graph with no cycles) consisting of n nodes numbered from 0 to n - 1 and exactly n - 1 edges. You are given a 0-indexed integer array vals of length n where vals[i] denotes the value of t

leetcode.com

길찾기 관련 문제가 계속 나오네 ㅠ_ㅠ
오늘도 무지성 솔루션 복붙 ㅠ_ㅠ

class Solution:
    def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
        n = len(vals)
        p = list(range(n))
        count = [Counter({vals[i]:1}) for i in range(n)] 
        edges = sorted((max(vals[i], vals[j]), i, j) for i, j in edges)
        res = n

        def find(i):
            if p[i] != i:
                p[i] = find(p[i])
            return p[i]

        for val, i, j in edges:
            pi, pj = find(i), find(j)
            res += count[pi][val] * count[pj][val]
            p[pi] = pj
            count[pj][val] += count[pi][val]
        
        return res
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.01.17 Today's Challenge  (0) 2023.01.17
2023.01.16 Today's Challenge  (0) 2023.01.16
Today's Challenge  (0) 2023.01.14
Today's Challenge  (0) 2023.01.13
Today's Challenge  (0) 2023.01.12
Comments