ν‹°μŠ€ν† λ¦¬ λ·°

πŸ‘©πŸ»‍πŸ’» λ¬Έμ œ

 

1021번: νšŒμ „ν•˜λŠ” 큐

첫째 쀄에 큐의 크기 Nκ³Ό 뽑아내렀고 ν•˜λŠ” 수의 개수 M이 주어진닀. N은 50보닀 μž‘κ±°λ‚˜ 같은 μžμ—°μˆ˜μ΄κ³ , M은 N보닀 μž‘κ±°λ‚˜ 같은 μžμ—°μˆ˜μ΄λ‹€. λ‘˜μ§Έ μ€„μ—λŠ” 지민이가 뽑아내렀고 ν•˜λŠ” 수의 μœ„μΉ˜κ°€

www.acmicpc.net


✍🏻 ν’€μ΄

🎨 Go

// https://www.acmicpc.net/problem/1021
// 덱을 ν™œμš©ν•˜μ—¬ 큐λ₯Ό νšŒμ „μ‹œν‚€λŠ” 문제
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n, m int
	fmt.Fscanln(reader, &n, &m)

	var q []queue
	for i := 0; i < n; i++ {
		tmp := queue{}
		tmp.curPos = i + 1
		tmp.initPos = i + 1
		q = append(q, tmp)
	}

	var selectPos []int
	for i := 0; i < m; i++ {
		var pos int
		fmt.Fscanf(reader, "%d ", &pos)
		selectPos = append(selectPos, pos)
	}

	var count int
	for len(selectPos) > 0 && len(q) > 0 {
		for i := 0; i < len(q); i++ {
			if q[i].initPos == selectPos[0] {
				if i < len(q)-i {
					count += i
					q = moveLeft(q, i)
				} else {
					count += (len(q) - i)
					q = moveRight(q, len(q)-i)
				}
				q = q[1:]
				selectPos = selectPos[1:]
				break
			}
		}
	}
	fmt.Fprintln(writer, count)
}

func moveLeft(q []queue, interval int) []queue {
	q = append(q[interval:], q[0:interval]...)
	return q
}

func moveRight(q []queue, interval int) []queue {
	q = append(q[len(q)-interval:len(q)], q[0:len(q)-interval]...)
	return q
}

type queue struct {
	curPos  int
	initPos int
}

🎨 Python3

# https://www.acmicpc.net/problem/1021
# 덱을 ν™œμš©ν•˜μ—¬ 큐λ₯Ό νšŒμ „μ‹œν‚€λŠ” 문제
import sys

class Queue:
     def __init__(self, cur_pos, init_pos):
        self.cur_pos = cur_pos
        self.init_pos = init_pos

def move_left(q, interval):
    result = []
    result.extend(q[interval:])
    result.extend(q[0:interval])
    return result

def move_right(q, interval):
    result = []
    result.extend(q[len(q)-interval:len(q)])
    result.extend(q[0:len(q)-interval])
    return result

if __name__ == "__main__":
    n, m = list(map(int, sys.stdin.readline().split()))
    
    q = []
    for i in range(n):
        q.append(Queue(i+1, i+1))
    
    select_pos = list(map(int, sys.stdin.readline().split()))
    count = 0
    while len(select_pos) > 0 and len(q) > 0:
        for i in range(len(q)):
            if q[i].init_pos == select_pos[0]:
                if i < len(q)-i:
                    count += i
                    q = move_left(q, i)
                else:
                    count += (len(q) - i)
                    q = move_right(q, len(q)-i)
                q = q[1:]
                select_pos = select_pos[1:]
                break
    print(count)
728x90
λŒ“κΈ€