Uva's 3n+1 problem

前端 未结 8 1951
滥情空心
滥情空心 2020-12-11 22:40

I\'m solving Uva\'s 3n+1 problem and I don\'t get why the judge is rejecting my answer. The time limit hasn\'t been exceeded and the all test cases I\'ve tried have run corr

相关标签:
8条回答
  • 2020-12-11 23:36

    This solution gets accepted within 0.5s. I had to remove the package modifier.

       import java.util.*;
    
        public class Main {
    
        static Map<Integer, Integer> map = new HashMap<>();
    
        private static int f(int N) {
            if (N == 1) {
                return 1;
            }
    
            if (map.containsKey(N)) {
                return map.get(N);
            }
    
            if (N % 2 == 0) {
                N >>= 1;
                map.put(N, f(N));
                return 1 + map.get(N);
            } else {
                N = 3*N + 1;
                map.put(N, f(N) );
                return 1 + map.get(N);
            }
        }
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
    
            try {
                while(scanner.hasNextLine()) {
                    int i = scanner.nextInt();
                    int j = scanner.nextInt();
    
                    int maxx = 0;
                    if (i <= j) {
                        for(int m = i; m <= j; m++) {
                            maxx = Math.max(Main.f(m), maxx);
                        }
                    } else {
                        for(int m = j; m <= i; m++) {
                            maxx = Math.max(Main.f(m), maxx);
                        }
                    }
                    System.out.println(i + " " + j + " " + maxx);
                }
                System.exit(0);
            } catch (Exception e) {
    
            }
    
    
        }
    }
    
    0 讨论(0)
  • 2020-12-11 23:37

    Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:

    10 1
    

    You should print

    10 1 20
    
    0 讨论(0)
提交回复
热议问题