줄이 6개니까 6개의 스택이 있다고 생각하고 진행하면 된다.
줄의 번호와 프랫 번호가 들어올 때 줄의 번호를 기준으로
1) 스택[줄의 번호] 비어있다 → 아무것도 없으니까 프랫 번호를 push하고 (프랫을 누르고) 하나 카운트 하기
2) 안 비어있다 → 이미 프랫번호를 누르고 있다
2.1) st[줄의 번호].top < 프랫 번호 → ex) 2번 줄의 5를 누르고 있는데 프랫 번호로 7이 들어옴. 그냥 누르면 되니까 push하고 카운트
2.2) st[줄의 번호]top == 프랫 번호 → 이미 누른 상태이므로 튕기기만 하면 됨. 카운트 할 필요 없음
3.3) st[줄의 번호].top > 프랫 번호 → ex) 2번 줄의 5를 누르고 있는데 3이 들어옴. 그럼 5를 떼어내야 하므로 떼어내기.
이 때, 2번 줄의 5뿐만 아니라 4를 누르고 있었다면 이것 또한 떼어 내야 하므로 st[줄의 번호].top < 프랫 번호가 될 때까지 반복
- C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include<iostream> #include<cstring> #include<stack> using namespace std; stack<int> st[7]; int main(void){ cin.tie(0); cout.tie(0); ios_base :: sync_with_stdio(false); int n,p,x,y,ans=0; cin >> n >> p; for(int i=0; i<n; i++){ cin >> x >> y; if(!st[x].empty()){ if(st[x].top()<y) { st[x].push(y); ans++;} else if(st[x].top()==y) continue; else { while(!st[x].empty() && (st[x].top()>y)){ st[x].pop(); ans++; } if(st[x].empty() || st[x].top()<y) { st[x].push(y); ans++; } } } else { st[x].push(y); ans++; } } cout << ans; return 0; } | cs |
- JAVA
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.Stack; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Stack<Integer>[] st = new Stack[7]; for(int i=0; i<7; i++) st[i] = new Stack<Integer>(); String[] str = br.readLine().split(" "); int n = Integer.parseInt(str[0]); int p = Integer.parseInt(str[1]); int ans=0; for(int i=0; i<n; i++){ str = br.readLine().split(" "); int number = Integer.parseInt(str[0]); int fret = Integer.parseInt(str[1]); if(!st[number].isEmpty()){ if(st[number].peek()<fret) { st[number].push(fret); ans++;} else if(st[number].peek()==fret) continue; else { while(!st[number].isEmpty() && (st[number].peek()>fret)){ st[number].pop(); ans++; } if(st[number].isEmpty() || st[number].peek()<fret ) { st[number].push(fret); ans++; } } } else { st[number].push(fret); ans++; } } System.out.print(ans); } } | cs |
만약 자바 코드에서 nullpointerexception 가 뜬다면 11~12코드 때문일 것..
'백준 1 > 자료구조' 카테고리의 다른 글
| [백준 2493] 탑 (C++/Python) (0) | 2021.01.15 |
|---|---|
| [백준 1406] 에디터 (Python) (0) | 2021.01.11 |
| [백준 3986] 좋은 단어 (C++/Python) (0) | 2020.12.06 |
| [백준 1935] 후위 표기식2 (C++/Java) (0) | 2020.12.06 |
| [백준 1918] 후위 표기식 (C++/Java) (0) | 2020.12.06 |