

-Code
import java.io.*;
import java.util.*;
public class Main {
static class PosInfo {
int x, y, score;
public PosInfo(int x, int y, int score) {
this.x = x;
this.y = y;
this.score = score;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
PosInfo posInfo = (PosInfo) o;
return x == posInfo.x && y == posInfo.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Set<PosInfo> posSet = new HashSet<>();
Deque<PosInfo> deq = new ArrayDeque<>();
// 시작점 셋팅 및 set과 deque 셋팅
PosInfo start = new PosInfo(0, 0, 1);
posSet.add(start);
deq.addLast(start);
int n = Integer.parseInt(br.readLine());
String move = br.readLine();
StringTokenizer st = new StringTokenizer(br.readLine());
int nowX = 0, nowY = 0;
// 이동에 따른 계산
for (int i = 0; i < n; i++) {
int nowScore = Integer.parseInt(st.nextToken());
char nowMove = move.charAt(i);
// 위치 바꾸기
if (nowMove == 'R') nowX++;
else if (nowMove == 'L') nowX--;
else if (nowMove == 'U') nowY--;
else if (nowMove == 'D') nowY++;
// 현재 블록 정보 셋팅
PosInfo nowPos = new PosInfo(nowX, nowY, nowScore);
if (posSet.contains(nowPos)) {
// 겹치는 블록이 나오기 전까지 제거
while (!deq.peekLast().equals(nowPos)) {
posSet.remove(deq.pollLast());
}
// 위 반복문이 끝나면 대기열 맨 위에 겹친 블록 제거
posSet.remove(deq.pollLast());
}
// 현재 값 set과 deq에 넣기
deq.addLast(nowPos);
posSet.add(nowPos);
}
// 남은 블록들 점수 계산
int answer = 0;
while (!deq.isEmpty()) {
answer += deq.pollLast().score;
}
System.out.println(answer);
br.close();
}
}
처음에 set을 써야 할 거 같은데 x, y의 값을 가지고 찾아야 해서 이 부분에 대해서 고민했습니다.
그때, 오버라이딩으로 세팅해야 하나 생각은 들었지만 정확하지 않아서 확인해 보니 그 부분은 맞아서 로직을 짰으나 제거 로직의 마지막 값 한 번 더 제거를 해야 하는 데 생각을 못해 빼먹어서 한 번 더 틀렸었습니다.
'알고리즘 문제 > Java' 카테고리의 다른 글
| [goormlevel/Java] RGB 주차장 (0) | 2026.06.12 |
|---|---|
| [goormlevel/Java] 어려운 문제 (0) | 2026.06.11 |
| [goormlevel/Java] [KOI 2017] 딱지놀이 (0) | 2026.06.09 |
| [goormlevel/Java] 계수기 만들기 (0) | 2026.06.08 |
| [goormlevel/Java] 소금물의 농도 구하기 (0) | 2026.06.07 |