1143 Lowest Common Ancestor (30分)

110 篇文章 0 订阅

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.

A binary search tree (BST) is recursively defined as a binary tree which has the following properties:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
Given any two nodes in a BST, 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), the number of pairs of nodes to be tested; and N (≤ 10,000), the number of keys in the BST, respectively. In the second line, N distinct integers are given as the preorder traversal sequence of the BST. Then M lines follow, each contains a pair of integer keys U and 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 BST, 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
6 3 1 2 5 4 8 7
2 5
8 7
1 9
12 -3
0 8
99 99
Sample Output:
LCA of 2 and 5 is 3.
8 is an ancestor of 7.
ERROR: 9 is not found.
ERROR: 12 and -3 are not found.
ERROR: 0 is not found.
ERROR: 99 and 99 are not found.

我自己写的,两个测试点超时,思路是先通过先序建立bst,因为是bst,所以只需要知道根结点就可以建树了,不用像网友们写的还得将其排序,求出中序再建树。然后找出两个结点的最小公共祖先,因为是bst,所以只需要找出第一个,两个结点在该结点两侧的结点即可,也就是一个大于该结点一个小于或者一个小于另一个大于,如果都大于,就去右子树继续找最小公共子结点。
判断树中有没有该结点用map记录即可,不要用数组,因为有负数。

#include<iostream>
#include<vector>
#include<cstdio>
#include<unordered_map>
using namespace std;
vector<int> preOrder;
unordered_map<int,int> hashTable;
struct node{
    int val;
    node* lchild, *rchild;
};
node* lca(int u, int v,node* root){
    if(u > root->val && v > root->val) lca(u,v,root->rchild);
    else if(u < root->val && v < root->val) lca(u,v,root->lchild);
    else return root;
}

node* insert(node* root, int val){
    if(root == nullptr){
        root = new node;
        root->val = val;
        root->lchild = root->rchild = nullptr;
    }
    else if(val >= root->val){
        root->rchild=insert(root->rchild,val);
    }
    else{
        root->lchild = insert(root->lchild,val);
    }
    return root;
}

node* build(node* root){
    for(int i = 0; i < preOrder.size(); i++){
        root = insert(root, preOrder[i]);
    }
    return root;
}

int main(){
    int m,n, x;
    cin>>m>>n;
    for(int i = 0; i < n; i++){
        cin>>x;
        preOrder.push_back(x);
        hashTable[x]++;
    }
    node* root = nullptr;
    root = build(root);
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(hashTable[u] == 0 && hashTable[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(hashTable[u] == 0){
            printf("ERROR: %d is not found.\n",u);
            continue;
        }
        else if(hashTable[v] == 0){
            printf("ERROR: %d is not found.\n",v);
            continue;
        }
        node* Node = lca(u,v,root);
        if(Node->val == u){
            printf("%d is an ancestor of %d.\n",u,v);
        }
        else if(Node->val == v){
            printf("%d is an ancestor of %d.\n",v,u);
        }
        else printf("LCA of %d and %d is %d.\n",u,v,Node->val);
    }
    return 0;
}

柳神的,在先序遍历中找到第一个可以让两个结点位于两侧的结点即可。根本不需要建树

#include<iostream>
#include<vector>
#include<cstdio>
#include<unordered_map>
using namespace std;
vector<int> preOrder;
unordered_map<int,int> hashTable;

int main(){
    int m,n, x;
    cin>>m>>n;
    for(int i = 0; i < n; i++){
        cin>>x;
        preOrder.push_back(x);
        hashTable[x]=1;
    }
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        int a;
        for(int j = 0; j < preOrder.size(); j++){
            a = preOrder[j];
            if((u>=a && v<=a) || (u<=a &&v>=a)) break;
        }
        if(hashTable[u]==0 && hashTable[v] == 0) printf("ERROR: %d and %d are not found.\n",u,v);
        else if(hashTable[u] == 0) printf("ERROR: %d is not found.\n",u);
        else if(hashTable[v] == 0) printf("ERROR: %d is not found.\n",v);
        else if(a == u || a==v) printf("%d is an ancestor of %d.\n",a,a==u?v:u);
        else printf("LCA of %d and %d is %d.\n",u,v,a);
    }
    return 0;
}

二刷,超时两个点,建树,建树细节和lca细节很多。均大于就去右子树找(无等于啊!!等于就是找到了),均小于就去左边找,其余情况就是找到了,直接return

#include<iostream>
#include<unordered_map>
#include<vector>
#include<cstdio>
using namespace std;
int m,n;
vector<int> preOrder;
unordered_map<int,int> ma;
struct node{
    int val;
    node* lchild, *rchild;
};

node* insert(node* root, int val){
    if(root == nullptr){
        root = new node;
        root->val = val;
        root->lchild = root->rchild = nullptr;
        return root;
    }
    else if(val >= root->val) root->rchild = insert(root->rchild,val);
    else if(val < root->val) root->lchild = insert(root->lchild,val);
    return root;
}

node* buildTree(node* root){
    for(int i = 0; i < preOrder.size(); i++){
        root = insert(root,preOrder[i]);
    }
    return root;
}

int lca(node* root, int u, int v){
    if(u > root->val && v>root->val) return lca(root->rchild,u,v);
    else if(u < root->val && v < root->val) return lca(root->lchild,u,v);
    else return root->val;
}

int main(){
    cin>>m>>n;
    preOrder.resize(n+1);
    for(int i = 0; i < n; i++){
        cin>>preOrder[i];
        ma[preOrder[i]]++;
    }
    node* root = nullptr;
    root = buildTree(root);
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(ma[u] == 0 && ma[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(ma[u] == 0 || ma[v] == 0){
            printf("ERROR: %d is not found.\n",ma[u] == 0 ? u :v);
            continue;
        }
        int ancestor = lca(root,u,v);
        if(ancestor == u || ancestor == v){
            printf("%d is an ancestor of %d.\n",ancestor,ancestor == u ? v:u);
        }
        else{
            printf("LCA of %d and %d is %d.\n",u,v,ancestor);
        }
    }
    return 0;
}

在中序和前序中找,超时一个点,不用建树,根据前序和中序序列,每次找根结点,判断根结点和uv大小。其余情况就是找到了。省了建树的时间

#include<iostream>
#include<unordered_map>
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
int m,n;
vector<int> preOrder;
vector<int> inOrder;
unordered_map<int,int> ma;
unordered_map<int,int> hashTable;//记录中序中给个结点的下标


int lca(int preL,int preR, int inL, int inR,int u, int v){
    int val = preOrder[preL];
    int subLeftTree = hashTable[val] - inL;
    if(u < val && v<val) return lca(preL+1,preL+subLeftTree,inL,inL+subLeftTree-1,u,v);
    else if(u >val && v> val) return lca(preL+subLeftTree+1,preR,inL+subLeftTree+1,inR,u,v);
    else return val;
}

int main(){
    cin>>m>>n;
    preOrder.resize(n+1);
    inOrder.resize(n+1);
    for(int i = 0; i < n; i++){
        cin>>inOrder[i];
        preOrder[i] = inOrder[i];
        ma[preOrder[i]]++;
    }
    sort(inOrder.begin(),inOrder.begin()+n);
    for(int i = 0; i < n; i++){
        hashTable[inOrder[i]] = i;
    }
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(ma[u] == 0 && ma[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(ma[u] == 0 || ma[v] == 0){
            printf("ERROR: %d is not found.\n",ma[u] == 0 ? u :v);
            continue;
        }
        int ancestor = lca(0,n-1,0,n-1,u,v);
        if(ancestor == u || ancestor == v){
            printf("%d is an ancestor of %d.\n",ancestor,ancestor==u?v:u);
        }
        else{
            printf("LCA of %d and %d is %d.\n",u,v,ancestor);
        }
    }
    return 0;
}

直接在前序序列里找,找到第一个大于等于u且小于等于v 或者 小于等于u且大于等于v的情况就是找到了

#include<iostream>
#include<unordered_map>
#include<vector>
#include<cstdio>
#include<algorithm>
using namespace std;
int m,n;
vector<int> preOrder;
unordered_map<int,int> ma;


int main(){
    cin>>m>>n;
    preOrder.resize(n+1);
    for(int i = 0; i < n; i++){
        cin>>preOrder[i];
        ma[preOrder[i]]++;
    }
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(ma[u] == 0 && ma[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(ma[u] == 0 || ma[v] == 0){
            printf("ERROR: %d is not found.\n",ma[u] == 0 ? u :v);
            continue;
        }
        int ancestor;
        for(int j = 0; j < n; j++){
            ancestor = preOrder[j];
            if((ancestor >= u && ancestor <= v) ||(ancestor <= u && ancestor >=v)) break;
        }
        if(ancestor == u || ancestor == v){
            printf("%d is an ancestor of %d.\n",ancestor,ancestor==u?v:u);
        }
        else{
            printf("LCA of %d and %d is %d.\n",u,v,ancestor);
        }
    }
    return 0;
}

这次用了bst的性质,中序遍历是从小到大的,前中建树然后lca就不会超时了,光用前序可能会超时(bst光用前序的话就是按顺序插入即可)。bst的lca不一样,如果均大于根结点,就去右边找,均小于就去左边,其余情况(包括u或者v等于根结点,一左一右这些情况),直接返回root即可

//bst的中序遍历是从小到大的,根据中序和前序来建树(光用中序有点难,光用中序建堆倒可以)
//bst的lca,如果当前结点的值大于u和v,就去左子树里找,如果小于就去右子树,如果一左一右,就是找到了
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
#include<cstdio>
using namespace std;
vector<int> preOrder;
vector<int> inOrder;
unordered_map<int,int> ma;
unordered_map<int,int> exist;
struct node{
    int val;
    node* lchild, *rchild;
};

node* buildTree(int preL,int preR,int inL,int inR){
    if(preL > preR) return nullptr;
    node* root = new node;
    root->val = preOrder[preL];
    root->lchild = root->rchild = nullptr;
    int subLeftTree = ma[preOrder[preL]] - inL;
    root->lchild = buildTree(preL+1,preL+subLeftTree,inL,inL+subLeftTree-1);
    root->rchild = buildTree(preL+subLeftTree+1,preR,inL+subLeftTree+1,preR);
    return root;
}

node* lca(node* root, int u,int v){
    //如果uv均小于根结点,就去左边找,反之右边。其余情况,包括一左一右和根结点等于u或者v都直接返回root
    if(root->val > u && root->val >v) return lca(root->lchild,u,v);
    else if(root->val < u && root->val <v) return lca(root->rchild,u,v);
    else return root;
}

int main(){
    int m,n;
    cin>>m>>n;
    preOrder.resize(n+1);
    inOrder.resize(n+1);
    for(int i = 0; i < n; i++){
        cin>>preOrder[i];
        inOrder[i] = preOrder[i];
        exist[inOrder[i]]++;
    }
    sort(inOrder.begin(),inOrder.begin()+n);
    for(int i = 0; i < n; i++){
        ma[inOrder[i]] = i;
    }
    node* root = new node;
    root = buildTree(0,n-1,0,n-1);
    int u,v;
    for(int i = 0; i < m; i++){
        cin>>u>>v;
        if(exist[u] == 0 && exist[v] == 0){
            printf("ERROR: %d and %d are not found.\n",u,v);
            continue;
        }
        else if(exist[u]==0 || exist[v]==0){
            printf("ERROR: %d is not found.\n",exist[u]==0?u:v);
            continue;
        }
        node* parent = lca(root,u,v);
        if(parent->val == u || parent->val ==v){
            printf("%d is an ancestor of %d.\n",parent->val,parent->val==u?v:u);
        }
        else{
            printf("LCA of %d and %d is %d.\n",u,v,parent->val);
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值