Day36力扣打卡

打卡记录

T 秒后青蛙的位置(DFS)

链接

python 复制代码
class Solution:
    def frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float:
        g = [[] for _ in range(n + 1)]
        for x, y in edges:
            g[x].append(y)
            g[y].append(x)
        g[1].append(0)
        ans = 0
        def dfs(x, fa, time, prod):
            if x == target and (time == 0 or len(g[x]) == 1):
                nonlocal ans
                ans = 1 / prod
                return True
            if x == target or time == 0: return False
            for y in g[x]:
                if y == fa: continue
                if dfs(y, x, time - 1, prod * (len(g[x]) - 1)): return True
            return False
        dfs(1, 0, t, 1)
        return ans

树上最大得分和路径(DFS)

链接

python 复制代码
class Solution:
    def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
        n = len(amount)
        g = [[] for _ in range(n)]
        for x, y in edges:
            g[x].append(y)
            g[y].append(x)
        g[0].append(-1)
        bob_time = [n] * n
        def dfs_bob(x: int, fa: int, t: int) -> bool:
            if x == 0:
                bob_time[x] = t
                return True
            for y in g[x]:
                if y != fa and dfs_bob(y, x, t + 1):
                    bob_time[x] = t
                    return True
            return False
        dfs_bob(bob, -1, 0)

        ans = -inf
        def dfs_alice(x: int, fa: int, alice_time: int, tot: int) -> None:
            if alice_time < bob_time[x]:
                tot += amount[x]
            elif alice_time == bob_time[x]:
                tot += amount[x] // 2
            if len(g[x]) == 1:
                nonlocal ans
                ans = max(ans, tot)
                return
            for y in g[x]:
                if y != fa:
                    dfs_alice(y, x, alice_time + 1, tot)
        dfs_alice(0, -1, 0, 0)
        return ans
相关推荐
Q_Q196328847513 分钟前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
ZYMFZ13 分钟前
python面向对象
前端·数据库·python
wangqiaowq13 分钟前
ImmutableList.of() 是 Google Guava 库 提供的一个静态工厂方法,用于创建一个不可变的(immutable)列表。
开发语言·windows·python
再卷也是菜23 分钟前
C++篇(14)二叉树进阶算法题
c++·算法
滑水滑成滑头24 分钟前
**发散创新:多智能体系统的探索与实践**随着人工智能技术的飞速发展,多智能体系统作为当今研究的热点领域,正受到越来越多关注
java·网络·人工智能·python
小邓儿◑.◑27 分钟前
贪心算法 | 每周8题(三)
算法·贪心算法
2401_8414956430 分钟前
【数据结构】最长的最短路径的求解
java·数据结构·c++·python·算法·最短路径·图搜索
小龙报33 分钟前
《算法每日一题(1)--- 连续因子》
c语言·开发语言·c++·windows·git·算法·visual studio
流浪大叔39 分钟前
Python下载实战技巧的技术文章大纲
开发语言·python