- 1143 Lowest Common Ancestor(30 分
- 1143 Lowest Common Ancestor(30 分
- 236. Lowest Common Ancestor of a
- Leetcode-235题:Lowest Common Ance
- Leetcode-236题:Lowest Common Ance
- LeetCode Lowest Common Ancestor
- lintcode 88. Lowest Common Ances
- 235. Lowest Common Ancestor of a
- [PAT] c++ 1143. Lowest Common An
- 236. Lowest Common Ancestor of a
对BST理解不深,程序运行不符合结果
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iomanip>
#include<map>
using namespace std;
int M, N, L, K, a, b, c;
vector<vector<int> > v;
vector<int> vm;
int main()
{
cin >> N >> M;
for (int i = 0; i < M; i++)
{
cin >> a;
vm.push_back(a - 1);
}
vector<int>::reverse_iterator it;
vector<int>::reverse_iterator it2;
for (int i = 0; i < N; i++)
{
cin >> b >> c;
bool flag1 = (find(vm.begin(), vm.end(), b - 1) != vm.end());//true表示找到
it = find(vm.rbegin(), vm.rend(), b - 1);
bool flag2 = (find(vm.begin(), vm.end(), c - 1) != vm.end());
it2 = find(vm.rbegin(), vm.rend(), c - 1);
if (flag1 == false && flag2 == false)
cout << "ERROR: " << b << " and " << c << " are not found." << endl;
if (flag1 == false && flag2 == true)
cout << "ERROR: " << b << " is not found." << endl;
if (flag1 == true && flag2 == false)
cout << "ERROR: " << c << " is not found." << endl;
if (flag1 == true && flag2 == true)
{
bool flag3 = false;
if (it2 > it)
{
swap(b, c);
flag3 = true;
}
if (b > c)
{
if (flag3 == true)
cout << c << " is an ancestor of " << b << "." << endl;
else
cout << b << " is an ancestor of " << c << "." << endl;
}
else
{
for (; it != vm.rend(); it++)
{
if ((*it) > (b - 1) && (*it) < (c - 1))
{
if (flag3 == true)
cout << "LCA of " << c << " and " << b << " is " << *it + 1 << "." << endl;
else
cout << "LCA of " << b << " and " << c << " is " << *it + 1 << "." << endl;
break;
}
}
if (it == vm.rend())
{
if (flag3 == true)
cout << "LCA of " << c << " and " << b << " is " << *(it - 1) + 1 << "." << endl;
else
cout << "LCA of " << b << " and " << c << " is " << *(it - 1) + 1 << "." << endl;
}
}
}
}
system("pause");
return 0;
}
网友评论