a644困難四柱河內塔差分區塊與大整數
CPE:The Priest Mathematician (UVa 10254)
利用最佳分割的增量規律預算到一萬個盤子。
解題思路
題目指定策略的遞推是 H(0)=0,H(n)=min₀≤k<n(2H(k)+2^(n−k)−1)。直接做一萬乘一萬次大整數比較成本高。此遞推的相鄰差分可分成區塊:1 出現 1 次、2 出現 2 次、4 出現 3 次,亦即 2^r 連續出現 r+1 次。
這個規律可由遞推的相鄰候選比較歸納:當前區塊結束於三角數 T(r)=(r+1)(r+2)/2,最優三柱部分的盤數維持 r+1 或 r+2;跨過三角數後,新增盤子的最小成本才翻倍。因此逐區塊累加差分即可產生所有 H(n)。Python 用內建大整數,C++ 以十進位字串加法實作倍增及累加,完全符合 C++17 而不依賴額外大數庫。n=0 輸出 0,輸入至 EOF。
Step-by-step animation
示意:前六個盤數的增量
步驟 1 / 3
第一區塊
增量 1 出現一次,H(1)=1。
Δ1=1
H1=1
- r
- 0
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string add(string a, string b) {
string out;
int i = (int)a.size() - 1, j = (int)b.size() - 1, carry = 0;
while (i >= 0 || j >= 0 || carry) {
int value = carry;
if (i >= 0)
value += a[i--] - '0';
if (j >= 0)
value += b[j--] - '0';
out += char('0' + value % 10);
carry = value / 10;
}
reverse(out.begin(), out.end());
return out;
}
int main() {
vector<string> answer(10001);
answer[0] = "0";
string step = "1";
int index = 1;
for (int repeat = 1; index <= 10000; ++repeat) {
for (int j = 0; j < repeat && index <= 10000; ++j, ++index)
answer[index] = add(answer[index - 1], step);
step = add(step, step);
}
int n;
while (cin >> n)
cout << answer[n] << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。