1005 繼續(3n+1)猜想 (25 分)java 實現
阿新 • • 發佈:2018-12-04
1005 繼續(3n+1)猜想 (25 分)
卡拉茲(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 (<100),第 2 行給出 K 個互不相同的待驗證的正整數 n (1<n≤100)的值,數字間用空格隔開。
輸出格式:
每個測試用例的輸出佔一行,按從大到小的順序輸出關鍵數字。數字間用 1 個空格隔開,但一行中最後一個數字後沒有空格。
輸入樣例:
6 3 5 6 7 8 11
輸出樣例:
7 6
程式碼如下:
import java.util.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); Integer[] a = new Integer[n]; HashMap<Integer, Integer> b = new HashMap<Integer,Integer>(); for(int i=0;i<n;i++) { int t = in.nextInt(); a[i] = t; while(t!=1) { if(t%2!=0) { t = (3*t)+1; } t = t / 2; if(b.get(t)!=null) { break; } b.put(t,1); } } Arrays.sort(a,new cmp()); int j = 0; for(int i=0;i<n;i++) { if(b.get(a[i])==null) { if(j!=0) { System.out.print(" "); } System.out.print(a[i]); j++; } } } } class cmp implements Comparator<Integer>{ @Override public int compare(Integer A, Integer B) { if(A!=B) { return B-A; } return 0; } }