티스토리 뷰

알고리즘

[leetcode] Number of Good Paths

조용한스택 2023. 1. 15. 18:37

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

Approach

1. 시작(혹은 끝)노드 값보다 작은 노드를 거쳐야 path로 인정되기 때문에 노드의 값이 더 높은 노드를 루트 노드로 본다.

2. 값이 같은 노드를 발견하면 path 를 합산한 뒤 하나의 노드로 합친다. 이 과정에서 같은 노드 값이 몇 개가 있는지 알아야 함.

3. 값이 작은 노드들부터 루트 노드를 찾고 path 계산을 해야 한다

 

Code

class Solution {
    vector<int> root;
    int find(int node) {
        if(root[node] == node) return node;
        return root[node] = find(root[node]);
    }
public:
    int numberOfGoodPaths(vector<int>& vals, vector<vector<int>>& edges) {
        int ans = vals.size();
        root.resize(vals.size());
        vector<int> v(vals.size());
        for(int i = 0; i < vals.size(); i++) {
            v[i] = 1;
            root[i] = i;
        }

		// vals 를 기준으로 정렬
        sort(edges.begin(), edges.end(), [&](vector<int>& a1, vector<int>& a2) {
            return max(vals[a1[0]], vals[a1[1]]) < max(vals[a2[0]], vals[a2[1]]);
        });

        for(auto& e : edges) {
            int a = find(e[0]);
            int b = find(e[1]);
            if(vals[a] != vals[b]) {
                if(vals[a] < vals[b]) root[a] = b;
                else root[b] = a;
            }
            else {
                ans += v[a] * v[b];
                root[b] = a;
                v[a] += v[b];
            }
        }

        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Sort - (3) Merge, Radix Sort  (0) 2021.12.22
Sort - (2) Quick, Heap Sort  (0) 2021.12.22
Sort - (1) Bubble, Selection, Insertion, Shell  (0) 2021.12.22
Sort - Intro  (0) 2021.12.22
[코딩테스트 log]보석 쇼핑  (0) 2021.07.02
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함