#12966: (C++) 0ms 的技巧


tntchn (tntchn)

學校 : 國立成功大學
編號 : 40564
來源 : [111.255.71.71]
最後登入時間 :
2020-07-14 04:36:38
c039. 00100 - The 3n + 1 problem -- UVa100 | From: [140.116.109.140] | 發表日期 : 2017-11-12 03:51

僅貼出關鍵部份程式碼
一樣是使用查表法
但在查的時候等到需要用到時再建表
邊查邊建不多花額外的時間做重複的計算
最後出來雖然用了一個 int [1000001] 表花費記憶體較多(2.1MB)
但將解題時間縮短到 0ms
把中間貼上來供大家參考~

vector<long long> stack;
stack.reserve(600);

// 計算過程中 t 最大可能到 1770189376 因此用 long long
long long t = i;

// 將 t 推進 stack 中, 找新 t 值直到找到 list[t]
while ((t>1000000)?1:list[t]==0) {   // 判斷式用來預防Segmentation fault
    stack.push_back(t);
    t = (t%2) ? 3 * t + 1 : t / 2;
}

// 以 list[t] 的值回推 i 數列的長度
// 並將 stack 中所有數的數列長度存起來供之後用
int counter = 1;
while (!stack.empty()) {
    if (stack.back()<=1000000) list[stack.back()] = list[t] + counter;
    stack.pop_back();
    counter++;
}
 
ZeroJudge Forum