zoukankan      html  css  js  c++  java
  • A1151 LCA in a Binary Tree (30分)

    一、技术总结

    二、参考代码

    #include <iostream>
    #include <vector>
    #include <map>
    using namespace std;
    map<int, int> pos;
    vector<int> in, pre;
    void lca(int inl, int inr, int preRoot, int a, int b) {
        if (inl > inr) return;
        int inRoot = pos[pre[preRoot]], aIn = pos[a], bIn = pos[b];
        if (aIn < inRoot && bIn < inRoot)
            lca(inl, inRoot-1, preRoot+1, a, b);
        else if ((aIn < inRoot && bIn > inRoot) || (aIn > inRoot && bIn < inRoot))
            printf("LCA of %d and %d is %d.
    ", a, b, in[inRoot]);
        else if (aIn > inRoot && bIn > inRoot)
            lca(inRoot+1, inr, preRoot+1+(inRoot-inl), a, b);
        else if (aIn == inRoot)
                printf("%d is an ancestor of %d.
    ", a, b);
        else if (bIn == inRoot)
                printf("%d is an ancestor of %d.
    ", b, a);
    }
    int main() {
        int m, n, a, b;
        scanf("%d %d", &m, &n);
        in.resize(n + 1), pre.resize(n + 1);
        for (int i = 1; i <= n; i++) {
            scanf("%d", &in[i]);
            pos[in[i]] = i;
        }
        for (int i = 1; i <= n; i++) scanf("%d", &pre[i]);
        for (int i = 0; i < m; i++) {
            scanf("%d %d", &a, &b);
            if (pos[a] == 0 && pos[b] == 0)
                printf("ERROR: %d and %d are not found.
    ", a, b);
            else if (pos[a] == 0 || pos[b] == 0)
                printf("ERROR: %d is not found.
    ", pos[a] == 0 ? a : b);
            else
                lca(1, n, 1, a, b);
        }
        return 0;
    }
    
  • 相关阅读:
    简单区间dp
    【题解】石子合并
    【2019.7.6】刷题记录
    【题解】大朋友的数字
    【基础】dp系列1
    【题解】垃圾陷阱
    【题解】导弹拦截
    hadoop各组件安装(非专业人士,不定期更新)
    python逼格提升
    python第三十二天-----算法
  • 原文地址:https://www.cnblogs.com/tsruixi/p/13189393.html
Copyright © 2011-2022 走看看