Posts [BOJ 백준] 10866번 덱 / C++
Post
Cancel

[BOJ 백준] 10866번 덱 / C++


Contents



문제


문제를 보시려면 링크를 클릭해주세요.


풀이


STL deque를 사용하여 풀었습니다.

덱이 비어 있을 때, pop_front(), pop_back(),front(), back() 함수 호출을 하면 런타임 에러가 발생할 수 있으므로 그 부분을 주의해 풀었습니다.


소스 코드


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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <deque>
#include <string>

using namespace std;

int main(int argc, char**argv) {

	ios::sync_with_stdio(0);
	cin.tie(0);
		
	deque<int> DQ;
	int N;
	
	cin >> N;
	
	while(N--){
		string str;
		cin >> str;
		
		if(str=="push_front"){
			int X;
			cin >> X;
			DQ.push_front(X);
		}
		
		else if(str=="push_back"){
			int X;
			cin >> X;
			DQ.push_back(X);
		}
		
		else if(str=="pop_front"){
			if(!DQ.empty()){
				cout << DQ.front() <<"\n";
				DQ.pop_front();
			}
			else
				cout << "-1\n";
		}
		
		else if(str=="pop_back"){
			if(!DQ.empty()){
				cout << DQ.back()<<"\n";
				DQ.pop_back();
			}
			else
				cout << "-1\n";
		}
		
		else if(str=="size"){
			cout << DQ.size() <<"\n";
		}
		
		else if(str=="empty"){
			cout << DQ.empty() <<"\n";
		}
		
		else if(str=="front"){
			if(!DQ.empty()){
				cout << DQ.front() <<"\n";
			}
			else
				cout << "-1\n";
		}
		
		else if(str=="back"){
			if(!DQ.empty()){
				cout << DQ.back() <<"\n";
			}
			else
				cout << "-1\n";
		}
	}		
	return 0;
}



This post is licensed under CC BY 4.0 by the author.

[BOJ 백준] 2164번 카드2 / C++

[BOJ 백준] 1021번 회전하는 큐 / C++

Comments powered by Disqus.