开发者

(Yet Another) UVa 3n+1 Help Question

I have been开发者_StackOverflow社区 beating my head against the wall trying to figure out why this is returning "Wrong Answer." I'd greatly appreciate any feedback.

Edit: I reposted the code, and this version finally fixed the "Runtime Error" by allowing for multiple spaces between the number pair. It now is saying "Wrong Answer" but as far as I can tell, I copied the given algorithm verbatim, so I'm at a loss.

Thanks.

The Problem

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;


public class Main {

public static void main(String[] args) {
   Main mine = new Main();
   mine.begin();
}

public void begin(){
    BufferedReader sys = new BufferedReader(new InputStreamReader(System.in));
    String[] pair;
    try{
        while((pair=sys.readLine().split(" +")).length==2){
            System.out.println(pair[0]+ " " +pair[1] + " " + getMax(Integer.parseInt(pair[0]),Integer.parseInt(pair[1])));
        }
    }catch(IOException ex){
        return;
    }
}

private String getMax(int a, int b){
    int maxcount,thiscount, num, n;

    for(maxcount = -1, num =Math.min(a, b); num <= Math.max(a, b); num++ ){
        for(n = num, thiscount = 1; n!=1; thiscount++){
            if(n%2==0)n=n/2;
            else n = 3*n +1;
        }
        if(thiscount>maxcount) maxcount = thiscount;
    }
    return String.valueOf(maxcount);
}
}


while(num<4){
...

Is the input always limited to 4 lines?


You might want to reconsider how you parse the lines. I believe the only lines that could have runtime errors in your code are the integer parsing ones. You're assuming that each i and j are separated by a single space. The question makes no mention of how much whitespace will be on a line.


If you're getting a wrong answer, and your program works on the samples, then the problem is probably tied to the fact that you're using ints rather then longs.

For the 3n+1 problem, the intermediate values can grow to be larger then an int can handle (2,147,483,647), and it's a common way for judge data to be evil.


I think the most important thing in UVA judge is:

  1. Get the output exactly the same. No extra lines at the end.
  2. Never throw exception just return or break with No output for Outside boundary parameters.
  3. Output is case sensitive
  4. Output parameters should maintain spaces as shown in the problem

Here is link at Stackoverflow : https://stackoverflow.com/a/14632770/1060656

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜