2018-03-05 Problem Solving►UVa UVa 100 - The 3n + 1 problem Contents 1. Problem2. Solution3. Code Problem題目網址中文網址 Solution在每次查詢時一邊建表,為了加速,已經算出的長度就不重複計算,並把過程中有出現過的數字,利用遞迴的概念(以stack去做),其長度都一一找出。 12345678int len = length[s.top()];s.pop();for (int j = 1; !s.empty(); j++, s.pop()){ now = s.top(); if (now < N) length[now] = len + j;} CodeUVa 10012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#include <cstdio>#include <stack>#define N 1000001typedef long long LL;int length[N] = {0, 1};void build(int n){ LL now = n, next; std::stack<LL> s; //for (int i = 2; i < N; i++) 也可以直接建完,速度較慢 s.push(now); while (now != 1) { next = (now & 1) ? ((now << 1) + now + 1) : (now >> 1); s.push(next); if (next < N && length[next]) break; now = next; } int len = length[s.top()]; s.pop(); for (int j = 1; !s.empty(); j++, s.pop()) { now = s.top(); if (now < N) length[now] = len + j; }}int main(){ //freopen("test.in", "r", stdin); //freopen("test.out", "w", stdout); int i, j; while (scanf("%d%d", &i, &j) != EOF) { int max = 0, a, b; if (i < j) a = i, b = j; else a = j, b = i; for (; a <= b; a++) { //邊建邊查 if (!length[a]) build(a); if (length[a] > max) max = length[a]; } printf("%d %d %d\n", i, j, max); } return 0;} Newer UVa 820 - Internet Bandwidth Older UVa 429 - Word Transformation