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,否则易超时,这样会在最后统一打印出答案
	}

}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值