题干:1143 Lowest Common Ancestor (30 分)
题解:用了45分钟,看了原先做了LCA的题目的题解,还是得14分。。。。我太难了,希望以后考试不考LCA,也是通过这道题认识到我对用复杂数据结构的题目还不是很熟练。。。。lca的这个模板,我综合了网络上的好多版本改写的,觉得还是我这个看起来容易理解一点。。。。但是感觉自己也是背不下来的。。。应该不会再考LCA吧,但是感觉考研考LCA的可能性挺大的。。。。
// A1143.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <bits/stdc++.h>
using namespace std;
#define max 10010
struct node {
int val;
node* lc;
node* rc;
node() {
val = 0;
lc = rc = NULL;
}
};
int m, n;
vector<int> pre;
vector<int> in;
vector<int> parent(max);
node* build(int root,int start,int end) {
if (start>end) {
return NULL;
}
int i = start;
for (i = 0; i < in.size(); i++) {
if (in[i] == pre[root]) {
break;
}
}
node* t = new node();
t->val = pre[root];
t->lc = build(root + 1, start, i - 1);
t->rc = build(root + 1 + i - start, i + 1, end);
return t;
}
void find_parent(node* root) {//implement via modify DFS
//cout << root->val << " ";
if (root->lc != NULL) {
parent[root->lc->val] = root->val;
find_parent(root->lc);
}
if (root->rc != NULL) {
parent[root->rc->val] = root->val;
find_parent(root->rc);
}
}
int lca(int x, int y, node* root) {
vector<bool> visited(max, false);
while (x != root->val) {
visited[x] = true;
x = parent[x];
}
visited[x] = true;
while (visited[y] == false && y <= n) {
y = parent[y];
}
return y;
}
int main()
{
#ifndef ONLINE_JUDGE
FILE* s;
freopen_s(&s, "in.txt", "r", stdin);
#endif // !ONLINE_JUDGE
cin >> m >> n;
//node root;
pre.resize(n);
in.resize(n);
for (int i = 0; i < n; i++) {
cin >> pre[i];
in[i] = pre[i];
}
sort(in.begin(), in.end());
node* root = NULL;
root = build(0, 0, n - 1);
find_parent(root);
//cout << endl;
int x, y, z;
for (int i = 0; i < m; i++) {
cin >> x >> y;
if ((y <= n && y >= 1) &&
(x <= n && x >= 1)
) {
z = lca(x, y, root);
if (z != x && z != y) {
printf("LCA of %d and %d is %d.\n", x, y, z);
}
if (z == x && z != y) {
printf("%d is an ancestor of %d.\n", x, y);
}
if (z != x && z == y) {
printf("%d is an ancestor of %d.\n", y, x);
}
if (z == x && z == y) {
printf("%d is an ancestor of %d.\n", x, y);
}
}
else if ((y<1 || y>n) && (x<1 || x>n)) {
printf("ERROR: %d and %d are not found.\n", x, y);
}
else if (y<1 || y>n) {
printf("ERROR: %d is not found.\n", y);
}
else if (x<1 || x>n) {
printf("ERROR: %d is not found.\n", x);
}
//cout << lca(x, y, root) << endl;
}
return 0;
return 0;
}