PAT 1005 Continue (3n+1) Conjecture (25 points) JAVA

1005 Continue (3n+1) conjecture (25 points)

The Callatz conjecture has been described in 1001. In this case, the situation is a little more complicated.

When we verify the Karaz conjecture, in order to avoid double counting, we can record every number encountered in the recursion process. For example, when verifying n=3, we need to calculate 3, 5, 8, 4, 2, 1, then when we verify n=5, 8, 4, 2, we can directly determine the Karaz conjecture , without repeated calculations, because these 4 numbers have already been encountered when verifying 3, we call 5, 8, 4, and 2 the numbers "covered" by 3. We call a number n in a sequence a "key number", if n cannot be covered by other numbers in the sequence.

Now given a series of numbers to be verified, we only need to verify a few key numbers, and we don't need to repeatedly verify the remaining numbers. Your task is to find these key numbers and output them in order from largest to smallest.

Input format:
each test input contains 1 test case, the first line gives a positive integer K (<100), the second line gives K different positive integers n to be verified (1<n≤100 ), the numbers are separated by spaces.

Output format:
The output of each test case occupies one line, and the key figures are output in descending order. Numbers are separated by 1 space, but there is no space after the last number on a line.

Input example:
6
3 5 6 7 8 11
Output example:
7 6
The code is as follows:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Main {
    
    
	
	static ArrayList<Integer> pass = new  ArrayList<Integer>();
	static ArrayList<Integer> key = new  ArrayList<Integer>();
	
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		
		//1.如果当前数不在覆盖集合,加入key,pass集合
		//2.对当前数做(3N + 1),
		//   (1).把产生数加入覆盖集合
		//   (2).如果key集合包含产生数,则移除			
		for (int i = 0; i < n; i++) {
    
    
			int num = sc.nextInt();			
			if( ! pass.contains(num) ) {
    
    
				pass.add(num);
				key.add(num);
				f(num);
			}			
		}
	
	    Collections.sort(key , new intComparator());
		for (int i = 0; i < key.size(); i++) {
    
    
			if( i == key.size() - 1 ) {
    
    
				System.out.print(key.get(i));
			}else {
    
    
				System.out.print(key.get(i) + " ");
			}		
		}		
	}
	
	public static void f(int n) {
    
    				
		while( n != 1 ) {
    
    	
			n = n % 2 == 0 ? n/2 : (3*n + 1)/2;			
			pass.add(n);
			if( key.contains(n) ) {
    
    
				key.remove((Object)n);
			}
		}	
	}	
	//自定义比较器
	//实现Comparator<>接口
	//重写compare方法
	public static class intComparator implements Comparator<Integer> {
    
    
		@Override
		public int compare(Integer o1, Integer o2) {
    
    
			return o2 - o1;
		}		
	}
}

Guess you like

Origin blog.csdn.net/fl6881688/article/details/121985520