더듬이의 헬로월드

Hello, World!

카테고리 없음

[백준/자료구조 1/C++] 10845-큐

더듬이 2021. 9. 15. 19:09
728x90

Bronze1


문제집 링크

https://www.acmicpc.net/workbook/view/3953

문제 링크

https://www.acmicpc.net/problem/10845


문제 해결 과정

자료구조의 한 종류인 큐를 잘 알고 있다면, 풀수 있는 문제였다.

STL의 queue를 이용하여 간단하게 구현하였다.

각 함수의 사용법을 숙지하면 간단하다!


주의할 점

1.오류가 날 수 있는 부분에서는 큐가 비어있는지 검사를 꼭 해주어야 한다!


코드

#include<iostream>
#include<queue>
using namespace std;

int main() {
	queue<int> BOJqueue;
	//STL queue선언
	int repeat;
	cin >> repeat;
	//명령 수 만큼 반복
	string cmd;//명령어를 저장할 문자열
	int x;//push시 입력 받을 변수
	for (int i = 0; i < repeat; i++)
	{
		cin >> cmd;

		if (cmd == "push") {
			cin >> x;
			BOJqueue.push(x);
		}
		else if (cmd == "pop") {
			if (BOJqueue.empty())
				cout << "-1" << " \n";
			else {
				cout << BOJqueue.front() << "\n";
				BOJqueue.pop();
			}
		}
		else if (cmd == "size")
			cout << BOJqueue.size() << "\n";
		else if (cmd == "empty")
			cout << BOJqueue.empty() << "\n";
		else if (cmd == "front") {
			if (BOJqueue.empty())
				cout << "-1" << " \n";
			else 
			cout << BOJqueue.front() << "\n";
		}
		else if (cmd == "back") {
			if (BOJqueue.empty())
				cout << "-1" << " \n";
			else 
			cout << BOJqueue.back() << "\n";
		}

	}
}


잘못된 부분이나 오해할 수 있는 부분이 있다면 언제든지 

댓글 남겨주시기 바랍니다!

728x90