[백준] 10845번, 18258번. 큐

leeeha·2021년 11월 3일
0

백준

목록 보기
16/185

관련 포스트
https://velog.io/@jxlhe46/백준-1920번.-수-찾기
https://velog.io/@jxlhe46/C-cin-cout-시간-초과-문제-해결-방법
https://velog.io/@jxlhe46/백준-2750-2751-10989번.-수-정렬하기


cin, cout을 사용할 때는 아래 코드를 작성해줘야 시간을 단축시킬 수 있다.

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

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

int main() {
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	queue<int> q;

	int n;
	cin >> n; // 명령어의 개수

	string str;

	for (int i = 0; i < n; i++) {
		cin >> str;

		if (str == "push") {
			int val;
			cin >> val;
			q.push(val);
		}
		else if (str == "pop") {
			if (!q.empty()) {
				printf("%d\n", q.front());
				q.pop();
			}
			else
				printf("-1\n");
		}
		else if (str == "size") {
			printf("%d\n", q.size());
		}
		else if (str == "empty") {
			printf("%d\n", q.empty());
		}
		else if (str == "front") {
			if (!q.empty())
				printf("%d\n", q.front());
			else
				printf("-1\n");
		}
		else if (str == "back") {
			if (!q.empty())
				printf("%d\n", q.back());
			else
				printf("-1\n");
		}
	}

	return 0;
}

10845번 (최대 1만개)

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

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

이 코드의 작성 여부에 따라 시간 차이가 상당히 난다.

18258번 (최대 200만개)

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

입력 크기가 200만개로 늘어났을 때는 시간 초과 문제가 발생하므로 반드시

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

이 코드를 작성해줘야 한다. 문제에 따라서는 이렇게 해도 시간초과가 발생하는 경우가 있는데, 이때는 알고리즘 자체를 시간복잡도가 더 낮은 것으로 구현해줘야 한다. (ex. 선형탐색 대신 이진탐색으로 구현)

profile
Keep Going!

0개의 댓글