티스토리 뷰

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
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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 29 30 31
글 보관함