-
[Python][C++] 10845번 큐Algorithm/Baekjoon 2024. 6. 29. 15:25
문제
https://www.acmicpc.net/problem/10845
코드
1. Python
import sys input = sys.stdin.readline n = int(input()) queue = [] for i in range(n): cmd = input().split() if cmd[0] == "push": queue.insert(0, cmd[1]) elif cmd[0] == "pop": if len(queue): print(queue.pop()) else: print(-1) elif cmd[0] == "size": print(len(queue)) elif cmd[0] == "empty": if len(queue): print(0) else: print(1) elif cmd[0] == "front": if !len(queue): print(-1) else: print(queue[len(queue) -1]) elif cmd[0] == "back": if !len(queue): print(-1) else: print(queue[0])
2. C++
#include <iostream> #include <queue> #include <string> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; queue<int> q; string cmd; int num; while (n--) { cin >> cmd; if (cmd == "push") { cin >> num; q.push(num); } else if (cmd == "pop") { if (q.empty()) cout << "-1\n"; else { cout << q.front() << "\n"; q.pop(); } } else if (cmd == "size") cout << q.size() << "\n"; else if (cmd == "empty") { if (q.empty()) cout << "1\n"; else cout << "0\n"; } else if (cmd == "front") { if (q.empty()) cout << "-1\n"; else cout << q.front() << "\n"; } else if (cmd == "back") { if (q.empty()) cout << "-1\n"; else cout << q.back() << "\n"; } } return 0; }
풀이
10828번과 같이 문제에서 요구한대로 큐를 구현하는 간단한 문제
'Algorithm > Baekjoon' 카테고리의 다른 글
[파이썬][C++] 11651번 좌표 정렬하기 2 (0) 2024.06.30 [Python][C++] 11650번 좌표 정렬하기 (0) 2024.06.30 [Python][C++] 10828번 스택 (0) 2024.06.29 [Python][C++] 10816번 숫자 카드 2 (0) 2024.06.28 [Python][C++] 10814번 나이순 정렬 (0) 2024.06.27