解題思路
不展開全部分枝就定位第K個顏色。
令G[t]為綠枝經t次變形的字串,Y[t]為黃枝;G[t]=Y[t−1]、Y[t]=G[t−1]Y[t−1]。
預計算兩類字串長度。從第1天的綠枝及t=N−1開始,若當前為綠就改黃並減t;若為黃,依K是否落在左側G區塊選分支,選右區塊時扣掉左側長度。
每次只保留包含第K個的那一塊,故最後t=0的顏色正是答案;起始長度不足K就−1。
每筆時間 O(N),工作空間 O(N)個任意精度長度。Python一次split另用 O(M)儲存全部查詢,且M<10。
Step-by-step animation
Fibonacci 字串的區塊定位逐步追蹤
步驟 1 / 3
步驟 1
第1天綠,表示0。
0
- 步驟
- 1
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using boost::multiprecision::cpp_int;
using ll = long long;
int main() {
vector<cpp_int> g(100, 1), y(100, 1);
for (int i = 1; i < 100; i++) {
g[i] = y[i - 1];
y[i] = g[i - 1] + y[i - 1];
}
int m;
cin >> m;
while (m--) {
int n;
cpp_int k;
cin >> n >> k;
int t = n - 1, c = 0;
if (k > g[t]) {
cout << -1 << '\n';
continue;
}
while (t) {
if (c == 0)
c = 1;
else if (k <= g[t - 1])
c = 0;
else
k -= g[t - 1];
t--;
}
cout << c << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。