문제 링크 : https://www.acmicpc.net/problem/1863
예시)
3
1 2
2 4
3 3
4 2
| x | 최소 빌딩 개수 |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 3 |
5
1 2 // 1번
2 4 // 2번
3 2 // 3번
4 1 // 4번
5 2 // 5번
1번, 3번, 5번은 모두 같은 건물 높이를 가지고 있다.
1번 input이 3번과 5번에 미치는 영향을 알아보자. 1번이 3번과 5번 모두에게 영향을 미칠까? 하나만 미칠까? 아니면 전혀 영향이 없을까?
3번에는 영향을 미치지만 5번은 영향을 미치지 않는다. 조금만 더 확장 시켜보면 4번 이후로 나오는 모든 건물들은 1번 input에 영향을 받지 않는다. 즉 특정 데이터는 특정 시점 이후로 삭제되어도 무방하다는 것을 의미한다.
특정 시점 이후로 삭제되어도 무방하다는 것을 다른 관점으로 해석해보면 상대적으로 최근의 데이터가 현재 시점의 정답을 결정하는데 영향을 미친다고 생각해볼 수 있다.
Stack 을 시도해보자.
다행이 stack으로 풀렸다!
import java.io.*;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;
public class Main {
static Counter counter;
static int N;
static class Counter {
Deque<Integer> stack;
int cnt;
public Counter() {
stack = new ArrayDeque<>();
cnt = 0;
}
public void add(int height) {
// 만약 stack의 탑보다 더 크다면 추가
if (stack.isEmpty() || height > top()) {
if(height == 0) return;
stack.addLast(height);
} else if (height < top()) {
// 작다면 top이 더 작아질 때까지 빼낸다.
while (!stack.isEmpty() && height < top()) {
int h = stack.pollLast();
cnt++;
}
add(height);
}
}
private int top() {
return stack.peekLast();
}
public int total() {
return cnt + stack.size();
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
N = Integer.parseInt(br.readLine());
counter = new Counter();
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
st.nextToken();
counter.add(Integer.parseInt(st.nextToken()));
}
sb.append(counter.total());
bw.write(sb.toString());
bw.flush();
bw.close();
}
}
boolean 배열을 사용한 히스토리 기록