문제: https://www.acmicpc.net/problem/2164
#include <bits/stdc++.h>
using namespace std;
queue<int> q;
int n;
int card;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) q.push(i);
for (int i = 0; i < n - 1; i++) {
q.pop();
card = q.front();
q.pop();
q.push(card);
}
cout << q.front() << '\n';
}
문제에서 수행하는 연산은 pop과 push 두 가지밖에 없다.
이때 연산을 수행하고 남은 카드의 개수에 집중해보면 카드가 1개 남기 위해선 pop연산을 n-1번 수행하면 된다.
때문에 반복문으로 pop과 push연산을 n-1번만큼 반복하면 자연스럽게 큐에는 카드 1개가 남게 되므로 해당 숫자를 출력하면 된다.
'알고리즘' 카테고리의 다른 글
[BOJ] 4949: 균형잡힌 세상 (0) | 2022.09.30 |
---|---|
[BOJ] 10886: 덱 (0) | 2022.09.29 |
[BOJ] 18258: 큐2 (0) | 2022.09.28 |
[BOJ] 10845: 큐 (0) | 2022.09.28 |
[BOJ] 1874: 스택 수열 (1) | 2022.09.28 |