1143 Lowest Common Ancestor(30 分)

对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;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容