斐波那契
程序员文章站
2022-06-19 11:23:28
...
斐波那契
10.23
**100 分做法:
我们来研究一下这个神秘的力量:
依次写下兔子们的标号和他们父亲(从 2 开始):
1 1 1 2 1 2 3 1 2 3 4 5 …
发现其实一定是许多连续段的从 1 开始的序列组合到一起,每段长度依次是斐波那契数列里面的每一项。
为什么会这样呢?**
之前多次二分去找父亲,然后就被卡了三个点的常数。【尴尬
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <map>
#define LL long long
using namespace std;
LL fi[100];
inline LL read(){
LL x = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); }
while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0'; ch = getchar(); }
return x * f;
}
int find(LL x){
int l=1, r=60;
while (l < r){
int mid = (l + r) >> 1;
if(fi[mid] < x) l = mid + 1;
else r = mid;
}
return l;
}
int main(){
//freopen ("fibonacci1.in", "r", stdin);
freopen ("fibonacci.in", "r", stdin);
freopen ("fibonacci.out", "w", stdout);
fi[1] = 1; fi[2] = 1;
for(int i=3; i<=60; i++){
fi[i] = fi[i-1] + fi[i-2];
//printf("%I64d\n", fi[i]);
}
int m; scanf("%d", &m);
while (m--) {
LL a = read(), b = read();
int x = find(a), y = find(b);
while (a != b) {
if (a > b) swap(a, b), swap(x, y);
while (fi[y] >= b) y--;
b = b - fi[y];
}
printf("%I64d\n", a);
}
return 0;
}