알고리즘

[BOJ] 2164: 카드2

haesa_s 2022. 9. 29. 16:33

문제: 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개가 남게 되므로 해당 숫자를 출력하면 된다.