已解决
7-3 有趣的最近公共祖先问题 分数 15
来自网友在路上 181881提问 提问时间:2023-11-05 06:30:09阅读次数: 81
最佳答案 问答题库818位专家为你答疑解惑
#include<iostream>
using namespace std;int n = 0, m = 0;
int FindAncestor(int* post, int* in, int a, int b, int size)
{int root = post[size - 1];if (root == a || root == b)return root;//中序遍历根的下标int rooti;for (rooti = 0; rooti < size; rooti++){if (root == in[rooti])break;}//找到a,b在中序遍历的下标int p = 0, q = 0;for (int i = 0; i < n; i++){if (a == in[i])p = i;if (b == in[i])q = i;}if (p < rooti && q < rooti) {FindAncestor(post, in, a, b, rooti);}else if (p > rooti && q > rooti) {FindAncestor(post + rooti, in + rooti + 1, a, b, size - rooti - 1);}else return in[rooti];
}
bool IsInTree(int* arr, int n, int x)
{for (int i = 0; i < n; i++){if (x == arr[i])return true;}return false;
}
int main()
{cin >> n >> m;int in[10000] = { 0 };int post[10000] = { 0 };for (int i = 0; i < n; i++)cin >> post[i];for (int i = 0; i < n; i++)cin >> in[i];while (m--){int a, b;cin >> a >> b;if (!IsInTree(post, n, a) || !IsInTree(post, n, b)){cout << "ERROR" << endl;continue;}cout << FindAncestor(post, in, a, b, n) << endl;}return 0;
}
查看全文
99%的人还看了
猜你感兴趣
版权申明
本文"7-3 有趣的最近公共祖先问题 分数 15":http://eshow365.cn/6-32480-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: linux环境下编译,安卓平台使用的luajit库
- 下一篇: 送你几款开源IDC资产管理系统