
자료 구조, 큐, 슬라이딩 윈도우
상근이는 환갑을 바라보던 나이에 수능 시험을 다시보고 교대에 입학했고, 초등학교 선생님으로 취직했다.
상근이네 반의 N명 학생들의 이름이 성적순으로 주어졌을 때, 좋은 친구가 몇 쌍이나 있는지 구하는 프로그램을 작성하시오. 좋은 친구는 등수의 차이가 K보다 작거나 같으면서 이름의 길이가 같은 친구이다.
첫째 줄에 N과 K가 주어진다. (3 ≤ N ≤ 300,000, 1 ≤ K ≤ N) 다음 N개 줄에는 상근이네 반 학생의 이름이 성적순으로 주어진다. 이름은 알파벳 대문자로 이루어져 있고, 2글자 ~ 20글자이다.
첫째 줄에 좋은 친구가 몇 쌍이 있는지 출력한다.
이름의 길이가 2 ~ 20 이기에, 이름의 길이별로 queue를 생성해서, 해당 큐에 이름의 인덱스를 저장한 뒤에, 큐에서 integer들을 빼내면서 빼낸 인덱스들을 다른 queue에 삽입하고, 큐의 길이를 더해주면 정답을 구할 수 있다.
import java.io.*;
import java.util.*;
class Main {
public static final BufferedReader BR = new BufferedReader(new InputStreamReader(System.in));
public static final BufferedWriter BW = new BufferedWriter(new OutputStreamWriter(System.out));
int N;
int K;
HashMap<Integer, Queue<Integer>> wordLengthTable;
public static void main(String[] args) throws Exception {
Main main = new Main();
main.init();
main.solution();
}
void init() throws Exception {
int[] inputArray = Arrays.stream(BR.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
N = inputArray[0];
K = inputArray[1];
wordLengthTable = new HashMap<>();
for (int i = 0; i < 21; i++) {
wordLengthTable.put(i, new ArrayDeque<>());
}
for (int i = 0; i < N; i++) {
String inputName = BR.readLine();
Queue<Integer> indexes= wordLengthTable.get(inputName.length());
indexes.add(i);
}
}
void solution() throws Exception {
long answer = 0;
for (int i = 2; i < 21; i++) {
Queue<Integer> indexes = wordLengthTable.get(i);
Queue<Integer> temp = new ArrayDeque<>();
while (indexes.size() > 0) {
Integer removed = indexes.remove();
while (temp.size() > 0 && removed - temp.peek() > K) {
temp.remove();
}
answer += temp.size();
temp.add(removed);
}
}
System.out.println(answer);
}
}
이렇게 유익한 내용을 공유해주셔서 감사합니다.