题目链接:https://img-my.csdn.net/uploads/201410/09/1412841673_6656.jpg
题目意思就是找一棵按上面链接所示的树对应的上面的两个点的最小公共祖先(LCP,Least Common Father),按照比较大小来依次返回自己的父亲节点就行了。具体看代码:getfather(a)函数是找父亲的代码
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
int three[20] , sum[20];
//int cnt = 0;
void init() {
three[0] = 1;
sum[0] = 0;
for(int i=1;i<20;i++) three[i] = three[i-1] * 3 , sum[i] = sum[i-1] + three[i];
}
int getfather(int a) {
if(a <= 3) return 0;
int i;
for(i=0;sum[i]<a;i++);
i --;
int tmp = (2+a-sum[i]) /3;
a = sum[i] - tmp + 1;
}
int LCP(int a,int b) {
while(a != b) {
if(a > b) a = getfather(a);
else b = getfather(b);
//printf("%d %d\n" , a , b);
//cnt ++;
//if(cnt > 5) break;
}
return a;
}
int main() {
int a , b;
init();
while(scanf("%d%d" , &a,&b) != EOF) {
//cnt = 0;
int ans = LCP(a , b);
printf("%d\n" , ans);
}
return 0;
}