acm java 快速读写_java_acm快速输入和输出

平常我们在用java做acm题目的时候,都是用

Scanner cin = new Scanner(System.in);

int num = cin.nextInt();

System.out.println(num);正常情况下都是是够用;不过当输入量和输出量太大的时候(达到百万到千万),那么这种输出方式就不够用了。

就用hdu上的1003题(MaxSum)作为例子:

这道题是是一个最大子串和问题,这个不是讨论的重点,在算法正确的写法(就是T*n耗时)之后发现内存爆了

0818b9ca8b590ca3270a3433284dd417.png

主要是上述输入和输出的时候消耗的。

我们改用字符流来读写数据的话,结果就变成了:

0818b9ca8b590ca3270a3433284dd417.png

这就是快速输入和输出的作用(当然我的代码可能不够完善,仅供借鉴)

AC代码如下:

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.io.Reader;

import java.io.Writer;

public class Main {

private static Reader reader = null;

private static Writer writer = null;

public static void main(String[] args) {

reader = new InputStreamReader(System.in);

writer = new OutputStreamWriter(System.out);

int n = getInt();

try {

for (int i = 1; i <= n; i++) {

int m, max = 0, sum, st, en, p;

int a;

if (i != 1) {

writer.write("\r\n");

writer.flush();

}

m = getInt();

sum = 0;

st = en = p = 0;

for (int j = 0; j < m; j++) {

a = getInt();

if (j == 0) {

max = a;

}

sum += a;

if (sum > max) {

max = sum;

st = p;

en = j;

}

if (sum < 0) {

sum = 0;

p = j + 1;

}

}

st++;

en++;

writer.write("Case " + i + ":" + "\r\n");

writer.write(max + " " + st + " " + en + "\r\n");

writer.flush();

}

} catch (Exception e) {

e.printStackTrace();

}

}

/**

* 获取键盘输入的整数

*

* @return 输入的整数

*/

public static int getInt() {

int read;

int res = 0;

boolean isNegative = false;// 是不是负数

try {

while ((read = reader.read()) != -1) {

if ((char) read == '-') {

res = 0;

isNegative = true;

break;

} else if (isNumber((char) read)) {

res = read - '0';

break;

}

}

while ((read = reader.read()) != -1) {

char ch = (char) read;

if (isNumber(ch)) {

res = res * 10 + (read - '0');

} else {

break;

}

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

if (isNegative == true) {

res = -1 * res;

}

return res;

}

/**

* 判断字符是否空白

*

* @param ch

* 字符

* @return 判断结果

*/

public static boolean isBlank(char ch) {

if (ch == '\r' || ch == '\n' || ch == ' ') {

return true;

}

return false;

}

/**

* 判断字符是不是数字

*

* @param ch

* 字符

* @return 判断结果

*/

public static boolean isNumber(char ch) {

if (ch <= '9' && ch >= '0') {

return true;

}

return false;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值