디시인사이드 갤러리

마이너 갤러리 이슈박스, 최근방문 갤러리

갤러리 본문 영역

1443. Minimum Time to Collect All Apples

개발뉴비갤로그로 이동합니다. 2023.01.11 23:41:03
조회 40 추천 0 댓글 0
														

https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/

 

Minimum Time to Collect All Apples in a Tree - LeetCode

Minimum Time to Collect All Apples in a Tree - Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex. The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not have any apple.   Example 1: [https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_1.png] Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false] Output: 8 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 2: [https://assets.leetcode.com/uploads/2020/04/23/min_time_collect_apple_2.png] Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false] Output: 6 Explanation: The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows. Example 3: Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false] Output: 0   Constraints: * 1 <= n <= 105 * edges.length == n - 1 * edges[i].length == 2 * 0 <= ai < bi <= n - 1 * fromi < toi * hasApple.length == n

leetcode.com


class Solution:

    def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
        cost = 0
        parent = [-1 for i in range(n)]
        dist = [-1 for i in range(n)]
        visit = [0 for i in range(n)]
        graph = [[] for i in range(n)]
        for x, y in edges:
            graph[x].append(y)
            graph[y].append(x)
        queue = deque([0])
        parent[0] = 0
        dist[0] = 0
        while queue:
            cur = queue.popleft()
            pos = dist[cur]
            for next in graph[cur]:
                if parent[next] == -1:
                    queue.append(next)
                    parent[next] = cur
                    dist[next] = pos + 1
        tour = [[p, x] for p, x in zip(dist, range(n))]
        for p, x in tour:
            if hasApple[x] == True :
                cur = x
                while cur != 0 and visit[cur] == 0:
                    hasApple[cur] = False
                    visit[cur] = 1
                    cur = parent[cur]
                cost += p - dist[cur]
        return 2*cost


부모와 루트에서의 거리가 있으면 된다는걸 보자마자 알았음.

dfs로 한번에 될 거 같기도 했는데.... 파이썬 재귀 깊이에 좀 자신이 없어서

bfs를 돌려서 부모와 거리를 구하고 역추적을 한 번 돌렸음

추천 비추천

0

고정닉 0

0

댓글 영역

전체 댓글 0
본문 보기

하단 갤러리 리스트 영역

왼쪽 컨텐츠 영역

갤러리 리스트 영역

갤러리 리스트
번호 제목 글쓴이 작성일 조회 추천
설문 2025년 가장 기억에 남는 인터넷 이슈는? 운영자 25/12/22 - -
85 909. Snakes and Ladders 이벤트ㅇㅅㅇ(219.251) 23.01.24 48 0
83 997. Find the Town Judge 이벤트ㅇㅅㅇ(219.251) 23.01.23 44 0
82 997. Find the Town Judge [1] 개발뉴비갤로그로 이동합니다. 23.01.23 74 0
81 백준 9996번 키비갤로그로 이동합니다. 23.01.23 56 0
78 마갤 입문함 [2] 키비갤로그로 이동합니다. 23.01.22 59 0
77 131. Palindrome Partitioning [1] 개발뉴비갤로그로 이동합니다. 23.01.22 58 0
75 93. Restore IP Addresses [1] 개발뉴비갤로그로 이동합니다. 23.01.21 72 0
74 Longest Palindromic Substring 5번 o오어o(14.37) 23.01.21 30 0
73 Restore IP Addresses 93번 o오어o(14.37) 23.01.21 38 0
72 안녕하세요 오늘부터 릿코 달리게씁니당 [2] 조르디(112.170) 23.01.21 54 0
71 491. Non-decreasing Subsequences [1] 개발뉴비갤로그로 이동합니다. 23.01.21 57 0
70 974. Subarray Sums Divisible by K [1] 개발뉴비갤로그로 이동합니다. 23.01.19 43 0
69 926. Flip String to Monotone Increasing [1] 개발뉴비갤로그로 이동합니다. 23.01.17 41 0
68 57. Insert Interval [1] 개발뉴비갤로그로 이동합니다. 23.01.17 37 0
66 트리 문제 두 개 개빡치네; 개발뉴비갤로그로 이동합니다. 23.01.15 48 0
65 1061. Lexicographically Smallest ~ 개발뉴비갤로그로 이동합니다. 23.01.15 42 0
64 여기 갤럼들은 전부 해외취업 준비중? [2] EvenAsura갤로그로 이동합니다. 23.01.14 106 0
63 1519. Number of Nodes in the Sub-Tree~ 개발뉴비갤로그로 이동합니다. 23.01.12 28 0
1443. Minimum Time to Collect All Apples 개발뉴비갤로그로 이동합니다. 23.01.11 40 0
59 230111 데일리 꽃지갤로그로 이동합니다. 23.01.11 68 0
58 100. Same Tree 개발뉴비갤로그로 이동합니다. 23.01.10 34 0
56 220110 데일리 꽃지갤로그로 이동합니다. 23.01.10 40 0
53 144. Binary Tree Preorder Traversal 개발뉴비갤로그로 이동합니다. 23.01.09 40 0
52 230109 데일리 꽃지갤로그로 이동합니다. 23.01.09 31 0
51 리트코드 4번 [4] o오어o(222.121) 23.01.09 65 0
50 리트코드 3번 o오어o(222.121) 23.01.09 25 0
49 220108 데일리 꽃지갤로그로 이동합니다. 23.01.08 54 0
48 68. Text Justification ㅇㅇ(12.50) 23.01.08 35 0
47 3번문제 코드 딱 한줄만 알려준다 ㅇㅇ(218.234) 23.01.08 37 0
46 코딩 테스트 tdd로 하시는 분 [1] TS(119.64) 23.01.07 61 0
45 가스스테이션(데일리) o오어o(222.121) 23.01.07 51 0
44 230107 데일리 [1] 꽃지갤로그로 이동합니다. 23.01.07 55 0
43 134. Gas Station 개발뉴비갤로그로 이동합니다. 23.01.07 47 0
42 1833. Maximum Ice Cream Bars 개발뉴비갤로그로 이동합니다. 23.01.06 58 0
41 230106 데일리 꽃지갤로그로 이동합니다. 23.01.06 50 0
38 오늘의 릿코드 Minimum Number of Arrows~ 개발뉴비갤로그로 이동합니다. 23.01.05 41 0
36 230105 데일리 [3] 꽃지갤로그로 이동합니다. 23.01.05 65 0
35 2244. Minimum Rounds 이거 푸는데 TS(119.64) 23.01.05 36 0
34 데일리 문제 어떻게 알아봄...? [1] TS(119.64) 23.01.05 40 0
33 230104 데일리 [2] 꽃지갤로그로 이동합니다. 23.01.04 86 0
31 Minimum Rounds to Complete All Task [1] 개발뉴비갤로그로 이동합니다. 23.01.04 102 0
30 944. Delete Columns to Make Sorted in TS ㅇㅇ(119.64) 23.01.04 43 0
29 백준 17726 Inheritance 꽃지갤로그로 이동합니다. 23.01.04 57 0
28 백준 14503번 로봇 청소기 개발뉴비갤로그로 이동합니다. 23.01.04 93 0
23 오늘의 릿코드 Delete Columns to Make Sorted [2] 개발뉴비갤로그로 이동합니다. 23.01.03 78 0
22 오늘의 데일리 [3] 꽃지갤로그로 이동합니다. 23.01.03 83 0
19 리트코드 해보면서 느낀 점 ㅇㅇ(119.64) 23.01.03 90 0
18 어쨌든 TS로 대문자 판별하기 문제 풀었는데 ㅇㅇ(119.64) 23.01.03 47 0
17 저는 js로 할게요 [5] ㅇㅇ(119.64) 23.01.03 80 0
16 오늘의 릿코드 Detect Capital 개발뉴비갤로그로 이동합니다. 23.01.02 61 1
갤러리 내부 검색
제목+내용게시물 정렬 옵션

오른쪽 컨텐츠 영역

실시간 베스트

1/8

디시미디어

디시이슈

1/2