1151 LCA in a Binary Tree (30分)

这个题建树=死亡,建树的时间+处理的时间 直接超时,哭都没地方哭。。。

应该利用原题目给出的序列进行稍加处理,利用找根的方法去挨个比较。
附本人代码(参考柳神):

#include
#include
#include
#include
#include
using namespace std;
int N, M;
vector<int>Vin, Vpost;
map<int, int>Ma;
void LCA(int begin, int end, int preroot, int a, int b) {
	if (begin<1 || end>N || end < begin)return;
	int root = Ma[Vpost[preroot]], ina = Ma[a], inb = Ma[b];
	if (ina < root&&inb < root)LCA(begin, root - 1, preroot + 1, a, b);
	else if (ina > root&&inb > root)LCA(root + 1, end, preroot + root - begin + 1, a, b);
	else if ((ina > root&&inb < root) || (ina<root&&inb>root))printf("LCA of %d and %d is %d.\n", a, b,Vin[root]);
	else if (ina == root)printf("%d is an ancestor of %d.\n", a, b);
	else if(inb==root)printf("%d is an ancestor of %d.\n", b, a);
}
int main() {
	int v1, v2;
	scanf("%d%d", &M, &N);
	Vin.resize(N+1);
	Vpost.resize(N+1);
	for (int i = 1; i <=N; i++) {
		scanf("%d", &Vin[i]);
		Ma[Vin[i]] = i;
	}
	for (int i = 1; i <=N; i++) {
		scanf("%d", &Vpost[i]);
	}
	for (int i = 0; i < M; i++) {
		scanf("%d%d", &v1, &v2);
		if (Ma[v1]==0 &&Ma[v2] == 0)printf("ERROR: %d and %d are not found.\n",v1,v2);
		else if (Ma[v1] == 0)printf("ERROR: %d is not found.\n", v1);
		else if (Ma[v2] == 0)printf("ERROR: %d is not found.\n", v2);
		else LCA(1, N , 1, v1, v2);
	}
	return 0;
}

你可能感兴趣的:(甲级代码精炼)