日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

1151 LCA in a Binary Tree 甲级

發布時間:2023/12/3 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 1151 LCA in a Binary Tree 甲级 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題意:

給定前序遍歷和中序遍歷,問u和v的lca
(先是中序,后是中序)

題解:

方法一:

參考題解
將樹映射到一顆BST上,在BST上找到答案然后再映射回原本的樹
方法二:
參考題解
已知某個樹的根結點,若a和b在根結點的左邊,則a和b的最近公共祖先在當前子樹根結點的左子樹尋找,如果a和b在當前子樹根結點的兩邊,在當前子樹的根結點就是a和b的最近公共祖先,如果a和b在當前子樹根結點的右邊,則a和b的最近公共祖先就在當前子樹的右子樹尋找。中序加先序可以唯一確定一棵樹,在不構建樹的情況下,在每一層的遞歸中,可以得到樹的根結點,在此時并入lca算法可以確定兩個結點的公共祖先~

代碼:

#include <iostream> #include <vector> #include <set> #include <cstring> #include <cstdio> #include <map>using namespace std;int m, n; int opre[10009], oin[10009]; int pre[10009], in[10009]; map<int, int> otos, stoo;int main() {cin >> m >> n;for (int i = 0; i < n; i++){cin >> oin[i];otos[oin[i]] = i;stoo[i] = oin[i];}for (int i = 0; i < n; i++){cin >> opre[i];pre[i] = otos[opre[i]];}for (int i = 0; i < m; i++){int u, v;int a;bool flag1 = true, flag2 = true;cin >> u >> v;if (otos.find(u) == otos.end())flag1 = false;if (otos.find(v) == otos.end())flag2 = false;if (!flag1 || !flag2){if (!flag1 && !flag2)printf("ERROR: %d and %d are not found.\n", u, v);elseprintf("ERROR: %d is not found.\n", flag1 == false ? u : v);continue;}u = otos[u];v = otos[v];for (int j = 0; j < n; j++){a = pre[j];if (a > u && a < v || a < u && a > v || a == u || a == v)break;}u = stoo[u];v = stoo[v];a = stoo[a];if (a == u || a == v)printf("%d is an ancestor of %d.\n", a, a == u ? v : u);elseprintf("LCA of %d and %d is %d.\n", u, v, a);}return 0; } #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.\n", 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.\n", a, b);else if (bIn == inRoot)printf("%d is an ancestor of %d.\n", 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.\n", a, b);else if (pos[a] == 0 || pos[b] == 0)printf("ERROR: %d is not found.\n", pos[a] == 0 ? a : b);elselca(1, n, 1, a, b);}return 0; }

總結

以上是生活随笔為你收集整理的1151 LCA in a Binary Tree 甲级的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。