하루하나코딩

백준 18258 : 큐 2 c++

HAHAKO 2023. 2. 2. 12:08

코드

#include <iostream>
#include <string>
#include <queue>

using namespace std;

int N, num;
string a;
queue<int> q;
	
	
int main(){
	
	cin.tie(NULL);
	ios.sync_with_stdio(false);
	
	cin >> N;
	
	for(int i = 0; i < N; i++){
		cin >> a;
		
		if(a == "push"){
			cin >> num;
			q.push(num);
		}
		else if(a == "pop"){
			if(!q.empty()){
				cout << q.front() << '\n';
				q.pop();	
			}
			else cout << -1 << '\n';			
		}
		else if(a == "size"){
			cout << q.size() << '\n';
		}
		else if(a == "empty"){
			cout << q.empty() << '\n';
		}
		else if(a == "front"){
			if(!q.empty()) cout << q.front() << '\n';	
			else cout << -1 << '\n';	
		}
		else {
			if(!q.empty()) cout << q.back() << '\n';	
			else cout << -1 << '\n';
		}	
	}
	return 0;
}

알게된 점

간단한 큐문제라 쉽게 stl이용해서 쉽게 풀었다.

근데 원래 stl 사용안하고 풀려했는데, 자꾸 시간초과 나와서.. 그냥 stl썼다.

근데 stl써도 시간초과 나오길래 왠지 확인했더니 

	cin.tie(NULL);
	ios.sync_with_stdio(false);

요 코드를 꼭 넣어줘야 했다.

 

ios_base::sync_with_stdio 구문은 c의 stdio와 cpp의 iostream을 동기화시켜주는 역할을 하는데, 이 때 iostream과 stdio의 버퍼를 모두 사용하기 때문에 딜레이가 발생한다고 한다.

 

따라서, ios_in_base::sync_with_stdio(false); 코드를 작성해줌으로써 동기화를 비활성화시켜줘서 시간을 단축시키는 것이다.

 

cin.tie는 평소 cin과 cout을 묶어준다. cout이 실행되지 않고도 cin이 실행되게끔 하는것이다. 입출력 시간을 절약할 수 있기 때문에 cin.tie(0) 코드를 많이 사용한다.