pat甲级1143 Lowest Common Ancestor (30分)

pat甲级1143 Lowest Common Ancestor (30分)

1.超时算法(测试点4超时)

复杂度: O ( m n log ⁡ n ) O(mn\log n) O(mnlogn),最坏情况 ( O ( m n 2 ) ) (O(mn^2)) (O(mn2))(每个结点出度不超过1且m,n取最大时超时)
代码如下:

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
vector<int> pre;
unordered_map<int,int> pos;

void LCA(int preRoot,int preL,int preR,int a,int b)
{
    int i=preRoot;
    while(i<=preR) if(pre[++i]>=pre[preRoot]) break;//i是右子树根位置
    if(preRoot==pos[a]) printf("%d is an ancestor of %d.\n",a,b);
    else if(preRoot==pos[b]) printf("%d is an ancestor of %d.\n",b,a);
    else if(pos[a]<i&&pos[b]<i) LCA(preRoot+1,preRoot+1,i-1,a,b);
    else if(pos[a]>=i&&pos[b]>=i) LCA(i,i,preR,a,b);
    else printf("LCA of %d and %d is %d.\n",a,b,pre[preRoot]);
}

int main()
{
    int m,n,U,V;
    cin>>m>>n;
    pre.reserve(n+1);
    for(int i=1;i<=n;++i)//不能从0开始,否则32行,33行条件判定语句出错
    {
        cin>>pre[i];
        pos[pre[i]]=i;
    }
    for(int i=0;i<m;++i)
    {
        cin>>U>>V;
        if(!pos[U]&&!pos[V]) printf("ERROR: %d and %d are not found.\n",U,V);
        else if(!pos[U]||!pos[V]) printf("ERROR: %d is not found.\n",pos[U]?V:U);
        else LCA(1,1,n,U,V);
    }
    return 0;
}

2.改进算法 ( O ( m n ) ) (O(mn)) (O(mn))

代码做点小手术:

void LCA(int preRoot,int preL,int preR,int a,int b)
{
    int i=preRoot;
    while(i<=preR) if(pre[++i]>=pre[preRoot]) break;//i是右子树根位置
    if(preRoot==pos[a]) printf("%d is an ancestor of %d.\n",a,b);
    else if(preRoot==pos[b]) printf("%d is an ancestor of %d.\n",b,a);
    else if(pre[preRoot]在a,b之间) printf("LCA of %d and %d is %d.\n",a,b,pre[preRoot]);
    else 
    {
        LCA(preRoot+1,preRoot+1,i-1,a,b);
        LCA(i,i,preR,a,b);
    }
}

在基本不改变算法复杂度的情况下,可以看出,函数实际上是沿着pre元素顺序依次递归,因此没有必要寻找右子树根位置,代码可以改进如下:
柳神代码
尽管只是优化一下算法,但代码大大简化,并且从运行时间33ms来看,针对测试用例还是很快的。不过缺点就是考试时,臣妾办不到,算法优化太特例化了。更有效率的通用化解决LCA算法我想应该还有,但臣妾还在学习中…坐等大佬翻牌子:)


更新

3.Tarjan算法 ( O ( n + m ) ) (O(n+m)) (O(n+m))

膜拜一波大佬:
日沉云起

4.倍增法

日沉云起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值