AcWing
  • 首页
  • 活动
  • 题库
  • 竞赛
  • 校园
  • 应用
  • 文章
    • 题解
    • 分享
    • 问答
  • 吐槽
  • 登录/注册

AcWing 1644. 二叉树中的最低公共祖先    原题链接    简单

作者: 作者的头像   打十铜人ing ,  2022-06-24 15:02:21 ,  所有人可见 ,  阅读 13


0


题目描述

blablabla

python非递归写法(递归爆栈)

from collections import deque
m,n=map(int,input().split())
order=list(map(int,input().split()))
pre=list(map(int,input().split()))

dic={}
q=deque([[0,n-1,0,n-1,0,float("inf")]])
while q:
    pl,pr,dl,dr,d,f=q.popleft()
    root=pre[pl]
    dic[root]=[f,d]
    k=order.index(root)
    if dl<k:
        q.append([pl+1,pl+1+(k-1-dl),dl,k-1,d+1,root])
    if k<dr:
        q.append([pl+1+(k-1-dl)+1,pr,k+1,dr,d+1,root])


for _ in range(m):
    a,b=map(int,input().split())
    if a not in dic and b not in dic:
        print("ERROR: {} and {} are not found.".format(a,b))
    elif a not in dic:
        print("ERROR: {} is not found.".format(a))
    elif b not in dic:
        print("ERROR: {} is not found.".format(b))
    else:
        fa=a
        fb=b
        da=dic[a][1]
        db=dic[b][1]
        while fa!=fb:
            if da<db:
                fb=dic[fb][0]
                db-=1
            else:
                fa=dic[fa][0]
                da-=1
        if fa==a:
            print("{} is an ancestor of {}.".format(a,b))
        elif fa==b:
            print("{} is an ancestor of {}.".format(b,a))
        else:
            print("LCA of {} and {} is {}.".format(a,b,fa))

0 评论

你确定删除吗?
1024
x

© 2018-2022 AcWing 版权所有  |  京ICP备17053197号-1
用户协议  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标
请输入绑定的邮箱地址
请输入注册信息