原题如下
题目大意
找出两个键值的最近共同祖先
自己的想法
一开始我打算先建树再遍历,后来发现不用建树直接遍历就行。
错误总结
错误1
就是已知中序、先序求后序的过程中经常犯的错误
post(prel + 1, prel + sum, inl, k - 1, u, v);
//错误的将sum写成了k,即:
//post(prel + 1, prel + k, inl, k - 1, u, v);
错误2
一个超时问题,在某一个东西相同且要求解多次的时候最好用一个变量将其存储起来,否则这道题会超时,一个4分的测试点:
else if (aIn < tree[root] && bIn < tree[root]) {
post(prel + 1, prel + sum, inl, k - 1, u, v);
//post(prel + 1, prel+k,inl, inRoot - 1, u, v);
}
else if (aIn > tree[root] && bIn > tree[root]) {
post(prel + sum + 1, prer, k + 1, inr, u, v);
//post(prel + 1 + (inRoot - inl), prer,inRoot + 1, inr, u, v);
}
以上的tree[root]可以用一个变量代替,否则多次从数组中取值会导致超时,改成如下:
int inRoot=tree[root];
else if (aIn < inRoot && bIn < inRoot) {
post(prel + 1, prel + sum, inl, k - 1, u, v);
//post(prel + 1, prel+k,inl, inRoot - 1, u, v);
}
else if (aIn > inRoot && bIn > inRoot) {
post(prel + sum + 1, prer, k + 1, inr, u, v);
//post(prel + 1 + (inRoot - inl), prer,inRoot + 1, inr, u, v);
}
AC代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cctype>
#include<cstring>
//#include<stdlib>
#include<algorithm>
#include<ctime>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<set>
#include<queue>
#include<map>
#include<stack>
#include<unordered_map>
using namespace std;
const int maxn = 10005;
int in[maxn], pre[maxn];
map<int, int> tree;
void post(int prel, int prer, int inl, int inr, int u, int v) {
if (inl > inr)return;
int root = pre[prel];
int inRoot = tree[pre[prel]], aIn = tree[u], bIn = tree[v];
int k = inRoot;
/*
for (k = inl; k <= inr; k++) {
if (in[k] == root)break;
}
*/
//if (inRoot == k)cout << "yes" << endl;
int sum = inRoot - inl;
if (root == u) {
printf("%d is an ancestor of %d.\n", u, v);
}
else if (root == v) {
printf("%d is an ancestor of %d.\n", v, u);
}
else if (aIn < inRoot && bIn < inRoot) {
post(prel + 1, prel + sum, inl, k - 1, u, v);
//post(prel + 1, prel+k,inl, inRoot - 1, u, v);
}
else if (aIn > inRoot && bIn > inRoot) {
post(prel + sum + 1, prer, k + 1, inr, u, v);
//post(prel + 1 + (inRoot - inl), prer,inRoot + 1, inr, u, v);
}
else if ((aIn > inRoot && bIn < inRoot) || (aIn<inRoot && bIn>inRoot)) {
printf("LCA of %d and %d is %d.\n", u, v, root);
}
}
int main() {
#ifdef testing
freopen("input.txt", "r", stdin);
#endif
int n, m;
cin >> m >> n;
for (int i = 1; i <= n; i++) {
cin >> in[i];
tree[in[i]] = i;
}
for (int i = 1; i <= n; i++) {
cin >> pre[i];
}
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
int flag_u = 0, flag_v = 0;
if (tree[u] == 0)flag_u = 1;
if (tree[v] == 0)flag_v = 1;
if (flag_u || flag_v) {
if (flag_u&&flag_v) {
printf("ERROR: %d and %d are not found.\n", u, v);
}
else {
int t = flag_u ? u : v;
printf("ERROR: %d is not found.\n", t);
}
}
else {
post(1, n, 1, n, u, v);
}
}
return 0;
}
结语
明天的战斗加油~