acm java 快速读写,java
平常我们在用java做acm题目的时候,都是用
Scanner cin = new Scanner(System.in);
int num = cin.nextInt();
System.out.println(num);正常情况下都是是够用;不过当输入量和输出量太大的时候(达到百万到千万),那么这种输出方式就不够用了。
就用hdu上的1003题(MaxSum)作为例子:
这道题是是一个最大子串和问题,这个不是讨论的重点,在算法正确的写法(就是T*n耗时)之后发现内存爆了
主要是上述输入和输出的时候消耗的。
我们改用字符流来读写数据的话,结果就变成了:
这就是快速输入和输出的作用(当然我的代码可能不够完善,仅供借鉴)
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;
}
}