PAT B1005 繼續(3n+1)猜想 (25 分)
阿新 • • 發佈:2019-02-10
!= 猜想 all algo ase spa 註意點 == out
卡拉茲(Callatz)猜想已經在1001中給出了描述。在這個題目裏,情況稍微有些復雜。
當我們驗證卡拉茲猜想的時候,為了避免重復計算,可以記錄下遞推過程中遇到的每一個數。例如對 n=3 進行驗證的時候,我們需要計算 3、5、8、4、2、1,則當我們對 n=5、8、4、2 進行驗證的時候,就可以直接判定卡拉茲猜想的真偽,而不需要重復計算,因為這 4 個數已經在驗證3的時候遇到過了,我們稱 5、8、4、2 是被 3“覆蓋”的數。我們稱一個數列中的某個數 n 為“關鍵數”,如果 n 不能被數列中的其他數字所覆蓋。
現在給定一系列待驗證的數字,我們只需要驗證其中的幾個關鍵數,就可以不必再重復驗證余下的數字。你的任務就是找出這些關鍵數字,並按從大到小的順序輸出它們。
輸入格式:
每個測試輸入包含 1 個測試用例,第 1 行給出一個正整數 K (<),第 2 行給出 K 個互不相同的待驗證的正整數 n (1)的值,數字間用空格隔開。
輸出格式:
每個測試用例的輸出占一行,按從大到小的順序輸出關鍵數字。數字間用 1 個空格隔開,但一行中最後一個數字後沒有空格。
輸入樣例:
6
3 5 6 7 8 11
輸出樣例:
7 6
#include <stdio.h> #include <algorithm> #include <string> #include <map> #include <iostream> #include<stack> using namespace std; const int maxn = 100; int index[111] = { 0 }; int main(){ int n; cin >> n; int count = 0; for (int i = 0; i < n; i++){ int x; cin >> x; if (index[x] == 0){ index[x] = 2; count++; }else if (index[x] == 1)continue; while (x != 1){ if (x % 2 == 0)x /= 2; else x = (3 * x + 1) / 2; if (x <= 100){ if (index[x] == 2){ count--; } index[x] = 1; } } } for (int i = 101; i > 0; i--){ if (index[i] == 2){ cout << i; count--; if (count != 0){ cout << ‘ ‘; } } } system("pause"); }
註意點:題目給的數雖然都小於100,但*3-1後會大於100,所以要加個條件判斷,不然會出現段錯誤,因為越界了
PAT B1005 繼續(3n+1)猜想 (25 分)