자료구조 Queue를 사용해서 푸는 문제.
문제에서 요구하는대로만 풀면 풀리는 쉬운 문제.
JS풀이와 C++풀이는 모두 동일하지만 JS는 이전에 큐 2문제에서 사용한 Queue 자료구조를 그대로 가져와 풀었다.
const fs = require('fs');
const input = fs.readFileSync('/dev/stdin').toString().trim().split('\n');
const N = Number(input[0]);
class Node {
prev = null;
next = null;
constructor(value) {
this.value = value;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(value) {
const newNode = new Node(value);
if (!this.head) this.head = newNode;
if (this.tail) {
this.tail.next = newNode;
newNode.prev = this.tail;
}
this.tail = newNode;
this.length += 1;
}
pop() {
if (this.length === 0) return -1;
const value = this.head.value;
this.head = this.head.next;
this.length -= 1;
return value;
}
size() {
return this.length;
}
empty() {
return this.length === 0 ? 1 : 0;
}
front() {
return this.length ? this.head.value : -1;
}
back() {
return this.length ? this.tail.value : -1;
}
}
const solution = (N) => {
const queue = new Queue();
for (let i = 1; i <= N; i++) queue.push(i);
while (queue.size() > 1) {
queue.pop();
const moved = queue.pop();
queue.push(moved);
}
return queue.front();
};
console.log(solution(N));
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
queue<int> Q;
int N;
cin >> N;
for (int i=1; i<=N; i++) Q.push(i);
while((int)Q.size() > 1) {
Q.pop();
int val = Q.front(); Q.pop();
Q.push(val);
}
cout << Q.front();
return 0;
}