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
相关推荐
飞Link1 分钟前
微调阶段中的模型自我提升、通用模型蒸馏和数据扩充
人工智能·算法·数据挖掘
70asunflower2 分钟前
Jupyter Notebook 详细快捷键操作指南
ide·python·jupyter
共享家95273 分钟前
力扣刷题之路
算法·leetcode·深度优先
开开心心_Every4 分钟前
免费视频画质增强:智能超分辨率无损放大
java·服务器·前端·python·学习·edge·powerpoint
FJW0208145 分钟前
Python面向对象三大特征封装,继承,多态
开发语言·python
我是一只小青蛙8886 分钟前
Windows下快速配置Python+OpenCV环境
python
开开心心_Every6 分钟前
免费AI图片生成工具:输入文字直接出图
服务器·前端·python·学习·edge·django·powerpoint
七夜zippoe8 分钟前
Python算法优化实战:时间与空间复杂度的艺术平衡
开发语言·python·算法·贪心算法·动态规划·复杂度
咚咚王者9 分钟前
人工智能之核心基础 机器学习 第十五章 数据预处理
人工智能·python·机器学习
青槿吖10 分钟前
【Java集合通关秘籍】从List到Set:解锁无序不重复的集合魔法✨
java·开发语言·算法