对两个节点分别求其到达根的路径序列,然后再求公共后缀即可
#include<iostream> #include<vector> using namespace std; vector<int> getPath(int x){ vector<int> path; while(x!=0){ path.push_back(x); x/=2; } return path; } int main(){ int x,y; while(cin>>x>>y){ vector<int> a=getPath(x),b=getPath(y); vector<int>::reverse_iterator it1 = a.rbegin(); vector<int>::reverse_iterator it2 = b.rbegin(); while(*it1==*it2){ it1++; it2++; if(it1==a.rend()||it2==b.rend()) break; } cout<<*(it1-1)<<endl; } return 0; }