LC 3108. 带权图里旅途的最小代价

https://leetcode.cn/problems/minimum-cost-walk-in-weighted-graph/description/

这题挺有意思的,需要稍微想想来简化问题。

class Solution:
    def minimumCost(self, n: int, edges: List[List[int]], query: List[List[int]]) -> List[int]:
        cut = [-1] * n
        adj = [[] for _ in range(n)]
        for u, v, w in edges:
            adj[u].append((v, w))
            adj[v].append((u, w))

        def dfs(x, c):
            cut[x] = c
            value = 0xffffffff
            for y, w in adj[x]:
                value &= w
                if cut[y] != -1: continue
                value &= dfs(y, c)
            return value

        c = 0
        values = []
        for i in range(n):
            if cut[i] != -1: continue
            value = dfs(i, c)
            values.append(value)
            c += 1

        ans = []
        for x, y in query:
            if cut[x] == cut[y]:
                ans.append(values[cut[x]])
            else:
                ans.append(-1)
        return ans