BOJ 5397:: 키로거
http://acmicpc.net/problem/5397
문자열과 커서가 나오는 문제는 이것 말고도 다양합니다. 풀이도 비슷하고요.
두 스택 front와 rear를 준비합니다. front는 커서 앞에 있는 문자들을 저장하고 rear는 커서 뒤에 있는 문자들을 저장합니다. 둘 다 처음엔 비어있습니다.
- 왼쪽 화살표 : front에서 pop하고 그걸 rear에 push합니다.
- 오른쪽 화살표 : rear에서 pop하고 그걸 front에 push합니다.
- 백스페이스 : front에서 pop합니다.
- 문자 입력 : front에 push합니다.
물론 pop 불가능하면 무시합니다.
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 44 45 46 47 48 49 |
#include<cstdio> #include<stack> using namespace std; char l[1000001]; int main(void) { int t; scanf("%d", &t); while (t--) { scanf("%s", l); stack<char> front, rear; for (int i = 0; l[i] != 0; i++) { if (l[i] == '<') { if (!front.empty()) { rear.push(front.top()); front.pop(); } } else if (l[i] == '>') { if(!rear.empty()) { front.push(rear.top()); rear.pop(); } } else if (l[i] == '-') { if (!front.empty()) front.pop(); } else front.push(l[i]); } while (!front.empty()) { rear.push(front.top()); front.pop(); } while (!rear.empty()) { printf("%c", rear.top()); rear.pop(); } printf("\n"); } return 0; } |