標籤:style blog http color java os strong io
The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime.
Input
The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each.
Output
Write a single integer to output, denoting how many integers ti are divisible by k.
題解:記錄這道題主要是為了記錄java中Scanner和BufferReader的區別,開始用Scanner,效率非常低,所以就TLE了。根據StackOverFlow裡面解釋:BufferReader只是從流中讀入資料,但不對資料做任何處理,Scanner按照需求解析資料並讀入,比如nextInt(),nextDouble()等。更詳細的答案還有這裡。
總結一下:
- A BufferedReader is a simple class meant to efficiently read from the underling stream.
- BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads.
- Scanner can parse the underlying stream for primitive types and strings using regular expressions.
- A scanner however is not thread safe, it has to be externally synchronized.
對於原文中的“ A scanner can do all that a BufferedReader can do and at the same level of efficiency as well.”不太認同,因為通過OJ來看,BufferReader的效率確實比Scanner高。
BufferReader的用法就用這道題的AC代碼記錄:
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 5 public class Main { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));10 try{11 String[] line =(bf.readLine()).split(" ");12 int n = Integer.parseInt(line[0]);13 int k = Integer.parseInt(line[1]);14 int count = 0;15 while(n-- > 0){16 int num = Integer.parseInt(bf.readLine());17 if(num%k == 0)18 ++count;19 }20 System.out.println(count);21 }22 catch(IOException e){23 System.out.print("input error");24 }25 }26 27 }