WEITST(SPOJ)的TLE

时间:2014-06-08 15:27:32

标签: java

我已经用Java编写了以下问题的代码,并在我的机器上得到了正确的答案。但是当我在SPOJ上提交它时,它会给出TLE(超出时间限制)错误。 有人可以帮我纠正/即兴吗?

[问题] http://www.spoj.com/problems/WILLITST/

以下是我尝试的代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
class WILLITST {
    public static void main(String[] args) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BigInteger n=BigInteger.valueOf(Long.parseLong(br.readLine()));
        ArrayList<BigInteger> al=new ArrayList<BigInteger>();
        BigInteger x=BigInteger.valueOf(2);
        BigInteger y=BigInteger.valueOf(3); 
        while(n.compareTo(BigInteger.ONE)==1){
            al.add(n);
            if(n.mod(x) == BigInteger.ZERO)
                n=n.divide(x);
            else n=y.multiply(n).add(y);
            if(al.contains(n))
            {
                System.out.println("NIE");
                return;
            }
        }
        System.out.println("TAK");
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:0)

成功提交以下代码,没有TLE:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.HashSet;
import java.util.Set;
class WILLITST_BigInteger {
    public static void main(String[] args) throws Exception {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        BigInteger n=BigInteger.valueOf(Long.parseLong(br.readLine()));
        Set<BigInteger> s=new HashSet<BigInteger>();
        BigInteger x=BigInteger.valueOf(2);
        BigInteger y=BigInteger.valueOf(3);
        while(n.compareTo(BigInteger.ONE)==1){
            if(!s.add(n)){
                System.out.println("NIE");
                return;
            }
            if((n.and(n.subtract(BigInteger.ONE))).equals(BigInteger.ZERO)){
                System.out.println("TAK");
                return;
            }
            if((n.and(BigInteger.ONE)).equals(BigInteger.ZERO))
                n=n.divide(x);
            else n=y.multiply(n).add(y);
        }
        System.out.println("TAK");
    }
}
相关问题