HDU 5047:JAVA输入输出的正确姿势

能用BigInteger耍赖是JAVA的一大特色,但是如果用我们熟知的输入输出方式又特别容易超时,特别是这道题似乎有意卡JAVA,不过还是被很多神牛弄过去了。

偷窥了几个队的代码,挑了一个最简单的记录了下来,还有一些BigInteger可能用得着的方法。


输入可以用代码中所示的Scanner sc = new Scanner(new BufferedInputStream(System.in)), 之后使用方法和原来的 = new Scanner(System.in)一样。

输出有点特别,PrintWriter如果不flush或者close是看不到输出的,但是如果每输出一点东西就flush这道题会超时,所以正确的姿势是全部完成以后一次性flush出来,这样就快了。

BigInteger的运算效率不用怀疑……


import java.io.*;
import java.math.BigInteger;
import java.util.*;

/*另外几个BigInteger常用方法:
 * add(BigInteger), substract(BigInteger), multiply(BigInteger), divide(BigInteger)加减乘除
 * BigInteger.valueOf(int) 把int转成BigInteger
 * BigInteger(String) 常用的构造函数
 * gcd(BigInteger) 
 * 
 */

public class Main 
{
	static int t;
	static BigInteger EIGHT = new BigInteger("8");
	static BigInteger SEVEN = new BigInteger("7");
	static BigInteger ONE = new BigInteger("1");
	
	public static void main(String[] args) throws IOException
	{
		Scanner sc = new Scanner (new BufferedInputStream(System.in));
		PrintWriter cout = new PrintWriter(System.out);
		t = sc.nextInt();
		
		int files;
		for(files=1; files<=t; files++)
		{
			String seq;
			seq = sc.next();
			BigInteger n = new BigInteger(seq);
			
			BigInteger ans;
			BigInteger ans2;
			
			ans = n.multiply(n).multiply(EIGHT);
			ans2 = n.multiply(SEVEN);//注意一定要写成a = a.multiply/add/substract/divide(b);
			ans = ans.subtract(ans2);
			ans = ans.add(ONE);
			
			cout.println("Case #"+files+": "+ans);
			
		}
		cout.flush();//最后flush,否则易超时,这样会在最后统一打印出答案
	}

}


你可能感兴趣的:(ACM练级日志)