๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ์ธ๊ณต๋ถ€/Algorithm

[๋ฐฑ์ค€][Node.js] 1966๋ฒˆ : ํ”„๋ฆฐํ„ฐ ํ

by ๐Ÿ‡๋ฐ•๋ด‰๋ด‰๐Ÿ‡ 2021. 7. 21.

 

 

Algorithm

-  ํ”„๋ฆฐํ„ฐ ํ -

 


 

๋ฌธ์ œ

์—ฌ๋Ÿฌ๋ถ„๋„ ์•Œ๋‹ค์‹œํ”ผ ์—ฌ๋Ÿฌ๋ถ„์˜ ํ”„๋ฆฐํ„ฐ ๊ธฐ๊ธฐ๋Š” ์—ฌ๋Ÿฌ๋ถ„์ด ์ธ์‡„ํ•˜๊ณ ์ž ํ•˜๋Š” ๋ฌธ์„œ๋ฅผ ์ธ์‡„ ๋ช…๋ น์„ ๋ฐ›์€ '์ˆœ์„œ๋Œ€๋กœ', ์ฆ‰ ๋จผ์ € ์š”์ฒญ๋œ ๊ฒƒ์„ ๋จผ์ € ์ธ์‡„ํ•œ๋‹ค.

์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ฌธ์„œ๊ฐ€ ์Œ“์ธ๋‹ค๋ฉด Queue ์ž๋ฃŒ๊ตฌ์กฐ์— ์Œ“์—ฌ์„œ FIFO - First In First Out ์— ๋”ฐ๋ผ ์ธ์‡„๊ฐ€ ๋˜๊ฒŒ ๋œ๋‹ค.

ํ•˜์ง€๋งŒ ์ƒ๊ทผ์ด๋Š” ์ƒˆ๋กœ์šด ํ”„๋ฆฐํ„ฐ๊ธฐ ๋‚ด๋ถ€ ์†Œํ”„ํŠธ์›จ์–ด๋ฅผ ๊ฐœ๋ฐœํ•˜์˜€๋Š”๋ฐ, ์ด ํ”„๋ฆฐํ„ฐ๊ธฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์กฐ๊ฑด์— ๋”ฐ๋ผ ์ธ์‡„๋ฅผ ํ•˜๊ฒŒ ๋œ๋‹ค.

 

1. ํ˜„์žฌ Queue์˜ ๊ฐ€์žฅ ์•ž์— ์žˆ๋Š” ๋ฌธ์„œ์˜ '์ค‘์š”๋„'๋ฅผ ํ™•์ธํ•œ๋‹ค.

2. ๋‚˜๋จธ์ง€ ๋ฌธ์„œ๋“ค ์ค‘ ํ˜„์žฌ ๋ฌธ์„œ๋ณด๋‹ค ์ค‘์š”๋„๊ฐ€ ๋†’์€ ๋ฌธ์„œ๊ฐ€ ํ•˜๋‚˜๋ผ๋„ ์žˆ๋‹ค๋ฉด, ์ด ๋ฌธ์„œ๋ฅผ ์ธ์‡„ํ•˜์ง€ ์•Š๊ณ  Queue์˜ ๊ฐ€์žฅ ๋’ค์— ์žฌ๋ฐฐ์น˜ ํ•œ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š๋‹ค๋ฉด ๋ฐ”๋กœ ์ธ์‡„๋ฅผ ํ•œ๋‹ค.

 

์˜ˆ๋ฅผ ๋“ค์–ด Queue์— 4๊ฐœ์˜ ๋ฌธ์„œ (A B C D)๊ฐ€ ์žˆ๊ณ , ์ค‘์š”๋„๊ณผ 2 1 4 3 ๋ผ๋ฉด C๋ฅผ ์ธ์‡„ํ•˜๊ณ , ๋‹ค์Œ์œผ๋กœ D๋ฅผ ์ธ์‡„ํ•˜๊ณ  A, B๋ฅผ ์ธ์‡„ํ•˜๊ฒŒ ๋œ๋‹ค.

 

์—ฌ๋Ÿฌ๋ถ„์ด ํ•  ์ผ์€, ํ˜„์žฌ Queue์— ์žˆ๋Š” ๋ฌธ์„œ์˜ ์ˆ˜์™€ ์ค‘์š”๋„๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์–ด๋–ค ํ•œ ๋ฌธ์„œ๊ฐ€ ๋ช‡ ๋ฒˆ์งธ๋กœ ์ธ์‡„๋˜๋Š”์ง€ ์•Œ์•„๋‚ด๋Š” ๊ฒƒ์ด๋‹ค. 

์˜ˆ๋ฅผ ๋“ค์–ด ์œ„์˜ ์˜ˆ์—์„œ C๋ฌธ์„œ๋Š” 1๋ฒˆ์จฐ๋กœ, A๋ฌธ์„œ๋Š” 3๋ฒˆ์งธ๋กœ ์ธ์‡„๋˜๊ฒŒ ๋œ๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

 

๋ฌธ์ œ ํ’€๊ธฐ

let fs = require("fs");
let input = fs.readFileSync("/dev/stdin")
	.toString()
	.trim()
	.split("\n");
let arr = input
	.slice(1, input.length)
	.map((el) => el.split(" ").map((el) => Number(el)));
let printBox = [];

for (let i = 0; i < arr.length; i += 2) {
	arr[i + 1][arr[i][1]] = String(arr[i + 1][arr[i][1]]);
	printBox.push(arr[i + 1]);
}

for (let i = 0; i < printBox.length; i++) {
	let count = 1;
	let box = printBox[i];
	let test = printBox[i].map((el) => Number(el));
	while (true) {
		let maxIndex = test.indexOf(Math.max(...test));
		if (maxIndex !== 0) {
			test = test.slice(maxIndex, test.length).concat(test.slice(0, maxIndex));
			box = box.slice(maxIndex, box.length).concat(box.slice(0, maxIndex));
		}
		if (typeof box[0] === "string") {
			console.log(count);
			break;
		} else {
			test.shift();
			box.shift();
			count++;
		}
	}
}

 

 

 

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€