In this problem, a tree is an undirected graph that is connected and has no cycles.
You are given a graph that started as a tree with n nodes labeled from 1 to n, with one additional edge added. The added edge has two different vertices chosen from 1 to n, and was not an edge that already existed. The graph is represented as an array edges of length n where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the graph.
Return an edge that can be removed so that the resulting graph is a tree of n nodes. If there are multiple answers, return the answer that occurs last in the input.
Example 1:
Input: edges = [[1,2],[1,3],[2,3]]
Output: [2,3]
Example 2:
Input: edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]
Output: [1,4]
Constraints:
- n == edges.length
- 3 <= n <= 1000
- edges[i].length == 2
- 1 <= ai < bi <= edges.length
- ai != bi
- There are no repeated edges.
- The given graph is connected.
제거 가능한 간선 중 가장 마지막 간선을 반환하는 문제입니다.
이미 노드 A에서 B로 갈 수 있는 어떤 임의의 경로가 존재한다면, 새로 추가된 간선 A-B는 제거해도 무방합니다.
(이미 간접 경로가 존재하므로)
따라서, 두 노드의 연결 여부를 판단하는 쿼리를 O(NlogN)의 시간복잡도 내에서 구현해야합니다.
(총 N<=1000개의 쿼리가 주어지므로)
따라서, 우리는 이 문제를 Disjoint Set을 활용해 풀 수 있다는 것을 알 수 있습니다.
(두 트리의 병합 및 연결 여부 판단을 O(logN)에 처리 가능)
=============================================================
코드는 아래와 같으며,
전체 시간 복잡도는 N(전체 쿼리 수) x logN(쿼리 복잡도) = O(NlogN)입니다,
'PS > Leetcode' 카테고리의 다른 글
[Leetcode Medium] 1268. Search Suggestions System (0) | 2022.06.19 |
---|---|
[Leetcode Hard] 745. Prefix and Suffix Search (0) | 2022.06.18 |
[Leetcode Medium] 934. Shortest Bridge (0) | 2022.05.23 |
[leetcode Hard] 2203. Minimum Weighted Subgraph With the Required Paths (0) | 2022.03.13 |
[leetcode medium] 211. 454. 4Sum II (0) | 2022.02.03 |