티스토리 뷰
https://www.acmicpc.net/problem/1327
1327번: 소트 게임
홍준이는 소트 게임을 하려고 한다. 소트 게임은 1부터 N까지 정수로 이루어진 N자리의 순열을 이용한다. 이 게임에선 K가 주어진다. 어떤 수를 뒤집으면, 그 수부터 오른쪽으로 K개의 수를 뒤집
www.acmicpc.net
class Node {
constructor(item) {
this.item = item;
this.next = null;
}
}
class Queue {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(item) {
const node = new Node(item);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
this.length += 1;
}
pop() {
const popItem = this.head;
this.head = this.head.next;
this.length -= 1;
return popItem.item;
}
}
const [[N, K], nums] = require('fs')
.readFileSync('./dev/stdin')
.toString()
.trim()
.split('\n')
.map((v) => v.split(' ').map(Number));
const set = new Set();
set.add(nums.join(''));
if (check(nums)) {
console.log(0);
process.exit();
}
function check(arr) {
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) return false;
}
return true;
}
const q = new Queue();
q.push([nums, 0]);
while (q.length > 0) {
const [x, cnt] = q.pop();
for (let i = 0; i + K <= N; i++) {
const head = x.slice(0, i);
const body = x.slice(i, i + K);
const tail = x.slice(i + K, N);
const reverse = [...head, ...body.reverse(), ...tail];
if (check(reverse)) {
console.log(cnt + 1);
process.exit();
} else {
const str = reverse.join('');
if (!set.has(str)) {
set.add(str);
q.push([reverse, cnt + 1]);
}
}
}
}
console.log(-1);
728x90
'자료구조 알고리즘 > 백준' 카테고리의 다른 글
Node.js) 백준 29614번: 학점 계산기 (0) | 2023.09.04 |
---|---|
Node.js) 백준 10987번: 모음의 개수 (0) | 2023.09.03 |
Node.js) 백준 17352번: 여러분의 다리가 되어 드리겠습니다! (0) | 2023.09.01 |
Node.js) 백준 2800번: 괄호 제거 (0) | 2023.09.01 |
Node.js) 백준 1374번: 강의실 (0) | 2023.08.31 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- DB 생성
- 그래프
- 면접질문
- 로드나인
- 투포인터
- 서버개발
- create db
- MySQL
- 투포인터 연습
- node.js
- 서버점검
- 개발자면접
- 다이나믹프로그래밍
- create databases;
- MOD
- 동적프로그래밍
- 롱베케이션
- 다이나밍프로그래밍
- 은둔청년체험
- BFS
- 최소공통조상
- 면접비
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함