PTA甲级 1151 LCA in a Binary Tree (C++)

The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both U and V as descendants.

Given any two nodes in a binary tree, you are supposed to find their LCA.

Input Specification:

Each input file contains one test case. For each case, the first line gives two positive integers: M ( ≤ 1 , 000 ) M (≤ 1,000) M(1,000), the number of pairs of nodes to be tested; and N ( ≤ 10 , 000 ) N (≤ 10,000) N(10,000), the number of keys in the binary tree, respectively. In each of the following two lines, N N N distinct integers are given as the inorder and preorder traversal sequences of the binary tree, respectively. It is guaranteed that the binary tree can be uniquely determined by the input sequences. Then M M M lines follow, each contains a pair of integer keys U U U and V V V. All the keys are in the range of int.

Output Specification:

For each given pair of U and V, print in a line LCA of U and V is A. if the LCA is found and A is the key. But if A is one of U and V, print X is an ancestor of Y. where X is A and Y is the other node. If U or V is not found in the binary tree, print in a line ERROR: U is not found. or ERROR: V is not found. or ERROR: U and V are not found..

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.

Caution:

这道题和普通的LCA问题最大的差别就是批量查询,如果一次查询的时间复杂度不够优秀的话很容易 TLE(leetcode上这道 LCA问题 是单次查询)。
在这道题上我用了存储父节点的方法还是 TLE 了,最后用了 Tarjan,但感觉处理的还是不是特别漂亮,尤其是 dfs 的过程中得到某一对询问的答案后这个答案的存储问题——这道题的不方便之处就是节点不是从 1 到 N 编号,所以没办法开表(理论上只能开一个INT_MAX * INT_MAX大小的表才能存储下所有的可能性),所以就用了一个很蠢的方法——每获得一个询问答案就把这一对询问和答案依次推入 res 数组(询问里的两个数按照较小数在前大数在后的顺序),然后输出的时候每次都找一遍。。。。

Solution 1 是 Tarjan 算法,Solution 2 是看了柳神的代码后写的。

Solution 1:

// Talk is cheap, show me the code
// Created by Misdirection 2021-08-30 17:13:58
// All rights reserved.

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

int n;
int inOrder[10010], preOrder[10010];

struct Node{
    int key;
    Node *left;
    Node *right;

    Node(int k = -1){
        key = k;
        left = NULL;
        right = NULL;
    }
    ~Node(){}
};

void findChildren(Node *r, int l1, int r1, int l2, int r2){
    if(r == NULL || l1 == r1) return;

    int posInMid = find(inOrder + l1, inOrder + n, r -> key) - inOrder;
    int posInPre = l2;

    int left = -1, right = -1;

    if(posInMid == l1){
        // 没有左子树
        right = preOrder[posInPre + 1];
    }
    else{
        // 有左子树
        left = preOrder[posInPre + 1];
        if(posInMid != r1) right = preOrder[posInMid - l1 + l2 + 1];
    }

    if(left != -1) r -> left = new Node(left);
    if(right != -1) r -> right = new Node(right);

    findChildren(r -> left, l1, posInMid - 1, l2 + 1, posInMid - l1 + l2);
    findChildren(r -> right, posInMid + 1, r1, posInMid - l1 + l2 + 1, r2);
}

void postTraverse(Node *r){
    if(r == NULL) return;

    if(r -> left != NULL) postTraverse(r -> left);
    if(r -> right != NULL) postTraverse(r -> right);
    cout << r -> key;
}

vector<vector<int>> asked;
unordered_map<int, bool> hasQuery;
unordered_map<int, int> position;
unordered_map<int, int> father;
unordered_map<int, bool> visited;
vector<int> res;

int findFather(int a){
    while(a != father[a]) a = father[a];
    return a;
}

void dfs(Node *r){
    visited[r -> key] = true;
    father[r -> key] = r -> key;

    if(hasQuery[r -> key]){
        int pos = position[r -> key];

        for(int i = 0; i < asked[pos].size(); ++i){
            if(visited[asked[pos][i]] == true){
                res.push_back(min(r -> key, asked[pos][i]));
                res.push_back(max(r -> key, asked[pos][i]));
                res.push_back(findFather(asked[pos][i]));
            }
        }
    }

    if(r -> left != NULL){
        dfs(r -> left);
        father[r -> left -> key] = r -> key;
    }
    if(r -> right != NULL){
        dfs(r -> right);
        father[r -> right -> key] = r -> key;
    }
}

int main(){
    int m;
    scanf("%d %d", &m, &n);
    // m - the number of pairs of nodes to be tested
    // n -  the number of keys in the binary tree

    unordered_map<int, bool> isOnTree;
    for(int i = 0; i < n; ++i){
        scanf("%d", &inOrder[i]);
        isOnTree[inOrder[i]] = true;
    }
    for(int i = 0; i < n; ++i) scanf("%d", &preOrder[i]);

    Node *root = new Node(preOrder[0]);
    findChildren(root, 0, n - 1, 0, n - 1);

    // for(int i = 0; i < n; ++i) printf("%d's father is %d\n", inOrder[i], father[inOrder[i]]);
    // postTraverse(root);
    
    vector<int> question;
    for(int i = 0; i < m; ++i){
        int a, b;
        scanf("%d %d", &a, &b);

        if(isOnTree[a] && isOnTree[b]){
            if(hasQuery[a] == false){
                hasQuery[a] = true;
                asked.push_back({b});
                position[a] = asked.size() - 1;
            }
            else{
                asked[position[a]].push_back(b);
            }

            if(hasQuery[b] == false){
                hasQuery[b] = true;
                asked.push_back({a});
                position[b] = asked.size() - 1;
            }
            else asked[position[b]].push_back(a);
        }

        question.push_back(a);
        question.push_back(b);
    }

    dfs(root);

    for(int i = 0; i < question.size(); i += 2){
        int a = question[i];
        int b = question[i + 1];

        if(isOnTree[a] && !isOnTree[b]) printf("ERROR: %d is not found.\n", b);
        else if(!isOnTree[a] && isOnTree[b]) printf("ERROR: %d is not found.\n", a);
        else if(!isOnTree[a] && !isOnTree[b]) printf("ERROR: %d and %d are not found.\n", a, b);
        else{
            int small = min(a, b);
            int big = max(a, b);
            int lca;

            for(int j = 0; j < res.size(); j += 3){
                if(res[j] == small && res[j + 1] == big) lca = res[j + 2];
            }

            if(lca == a) printf("%d is an ancestor of %d.\n", a, b);
            else if(lca == b) printf("%d is an ancestor of %d.\n", b, a);
            else printf("LCA of %d and %d is %d.\n", a, b, lca);
        }
    }

    return 0;
}

在这里插入图片描述

Solution 2:

// Talk is cheap, show me the code
// Created by Misdirection 2021-08-30 17:13:58
// All rights reserved.

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

int n;
int inOrder[10010], preOrder[10010];
unordered_map<int, int> posInPre, posInMid;

void lca(int l1, int r1, int l2, int r2, int a, int b){
    // l1 和 r1 是前序
    // l2 和 r2 是中序
    if(l1 > r1) return;

    int posA = posInMid[a];
    int posB = posInMid[b];
    int rootInMid = posInMid[preOrder[l1]];

    if((posA > rootInMid && posB < rootInMid) || (posA < rootInMid && posB > rootInMid))
        printf("LCA of %d and %d is %d.\n", a, b, preOrder[l1]);
    
    else if(posA == rootInMid) printf("%d is an ancestor of %d.\n", a, b);
    else if(posB == rootInMid) printf("%d is an ancestor of %d.\n", b, a);
    else if(posA < rootInMid && posB < rootInMid)
        lca(l1 + 1, rootInMid - l2 + l1, l2, rootInMid - 1, a, b);
    else if(posA > rootInMid && posB > rootInMid)
        lca(rootInMid - l2 + l1 + 1, r1, rootInMid + 1, r2, a, b);

}

int main(){
    int m;
    scanf("%d %d", &m, &n);
    // m - the number of pairs of nodes to be tested
    // n -  the number of keys in the binary tree

    unordered_map<int, bool> isOnTree;
    for(int i = 0; i < n; ++i){
        scanf("%d", &inOrder[i]);
        isOnTree[inOrder[i]] = true;
        posInMid[inOrder[i]] = i;
    }
    for(int i = 0; i < n; ++i){
        scanf("%d", &preOrder[i]);
        posInPre[preOrder[i]] = i;
    }
    
    for(int i = 0; i < m; ++i){
        int a, b;
        scanf("%d %d", &a, &b);

        if(isOnTree[a] && !isOnTree[b]) printf("ERROR: %d is not found.\n", b);
        else if(!isOnTree[a] && isOnTree[b]) printf("ERROR: %d is not found.\n", a);
        else if(!isOnTree[a] && !isOnTree[b]) printf("ERROR: %d and %d are not found.\n", a, b);
        else lca(0, n - 1, 0, n - 1, a, b);

    }

    return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

负反馈循环

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值