
오늘은 오랜만에 다시 PS를 풀어보려고 하는데..
C++에서 Java로 PS를 하려고 하니 적응이 안된다.
그래서 Java에서의 PS 팁을 조금 정리하려고 한다.
계속해서 업데이트 할 예정.
C++에서도 그렇지만 Java에서도 좀더 빠른 입출력 방법이 존재한다.
결론만 이야기하면 BufferedReader와 BufferedWriter를 이용해서 입출력을 수행해야한다.
example)
class Main {
private static int n;
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
n = Integer.parseInt(br.readLine());
ArrayList<Integer> list = new ArrayList<>();
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
list.add(Integer.parseInt(st.nextToken()));
}
int v = Integer.parseInt(br.readLine());
long result = list.stream().filter(integer -> {
return integer == v;
}).count();
bw.write(String.valueOf(result));
bw.flush();
}
}
다만, Scanner를 사용할때보다 조금 불편한게 String으로 받기때문에 별도의 형변환처리가 필요하고 1줄 전체를 입력받기 때문에 Stringtokenizer 처리도 별도로 필요하다.
C++에서도 그랬지만 자바에서도 EOF가 입력될때까지 수행해야하는 경우가 있다.
example)
public static void main(String[] args) throws IOException {
String s = "";
while ( (s = br.readLine()) != null && !s.isEmpty()) {
StringTokenizer st = new StringTokenizer(s);
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
bw.write(a+b+"\n");
}
bw.flush();
}
C++에서는 STL의 pair을 유용하게 사용했지만, 자바에서는 없다..
그래서 기본적으로 간단하게 만들어서 사용해야한다.
자바에서는 여러가지 방법으로 정렬을 지원한다.
1) Collections.sort()
2) List.sort()
3) 사용자 정의
example)
class Main {
public static class Pair {
public int value;
public int index;
public Pair(int value, int index) {
this.value = value;
this.index = index;
}
}
public static class PairComparator implements Comparator<Pair> {
@Override
public int compare(Pair o1, Pair o2) {
if (o1.value > o2.value) {
return 1;
} else if (o1.value < o2.value) {
return -1;
} else {
return 0;
}
}
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
ArrayList<Pair> list = new ArrayList<>();
for (int i = 0; i < 9; i++) {
int value = scanner.nextInt();
list.add(new Pair(value, i + 1));
}
Collections.sort(list, new PairComparator());
System.out.println(list.get(8).value + " " + list.get(8).index);
}
}