PAT_甲级_1151 LCA in a Binary Tree (30point(s)) (C++)【LCA倍增法】

目录

1,题目描述

 题目大意

2,思路

3,AC代码

4,解题过程


1,题目描述

Sample Input:

6 8
7 2 3 4 6 5 1 8
5 3 7 2 6 4 8 1
2 6
8 1
7 9
12 -3
0 8
99 99

 

Sample Output:

LCA of 2 and 6 is 3.
8 is an ancestor of 1.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

 题目大意

找出一棵树中两个节点的LCA(lowest common ancestor),注意节点可能不在树上;

 

2,思路

PAT_甲级_1143 Lowest Common Ancestor (30point(s)) (C++)【BST构建/寻找LCA/倍增法】

好像是一模一样的题目。。。

 

3,AC代码

终于体会到手指在键盘上飞舞的快感了!

 

#include<bits/stdc++.h>
using namespace std;
int N, M, in[10005], key;
struct node{
    int key, father, level;
}pre[10005];
void createTree(int root, int left, int right, int father, int level){
    if(left > right) return;
    pre[root] = {pre[root].key, father, level};
    int i = left;
    while(i <= right && pre[root].key != in[i])
        i++;
    createTree(root+1, left, i-1, root, level+1);
    createTree(root+(i-left)+1, i+1, right, root, level+1);
}
int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    scanf("%d%d", &M, &N);
    for(int i = 0; i < N; i++)
        scanf("%d", &in[i]);
    for(int i = 0; i < N; i++){
        scanf("%d", &key);
        pre[i] = {key, -1, -1};
    }
    createTree(0, 0, N-1, -1, 1);
    while(M--){
        int a, b, A = N, B = N;
        scanf("%d%d", &a, &b);
        for(int i = 0; i < N; i++){
            if(pre[i].key == a)
                A = i;
            if(pre[i].key == b)
                B = i;
        }
        if(A == N && B == N)
            printf("ERROR: %d and %d are not found.\n", a, b);
        else if(A == N)
            printf("ERROR: %d is not found.\n", a);
        else if(B == N)
            printf("ERROR: %d is not found.\n", b);
        else{
            bool flag = true;
            if(pre[A].level < pre[B].level){    
                flag = false;
                swap(A, B);
            }
            while(pre[A].level > pre[B].level)// !!!大于号
                A = pre[A].father;
            if(pre[A].key == pre[B].key)
                printf("%d is an ancestor of %d.\n", flag ? b : a, flag ? a : b);
            else{
                while(pre[A].key != pre[B].key){
                    A = pre[A].father;
                    B = pre[B].father;
                }
                printf("LCA of %d and %d is %d.\n", a, b, pre[A].key);
            }
        }
    }
    return 0;
}

4,解题过程

一发入魂o(* ̄▽ ̄*)ブ

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值