ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป ๋ฌธ์ œ

 

1158๋ฒˆ: ์š”์„ธํ‘ธ์Šค ๋ฌธ์ œ

์ฒซ์งธ ์ค„์— N๊ณผ K๊ฐ€ ๋นˆ ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ˆœ์„œ๋Œ€๋กœ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ K ≤ N ≤ 5,000)

www.acmicpc.net


โœ๐Ÿป ํ’€์ด

๐ŸŽจ Go

// https://www.acmicpc.net/problem/1158
package main

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

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

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

	result := Josephus(n, k)
	for i := 0; i < len(result); i++ {
		if i == 0 {
			fmt.Fprintf(writer, "<%d", result[i])
		} else {
			fmt.Fprintf(writer, ", %d", result[i])
		}
	}
	fmt.Fprintln(writer, ">")
}

func Josephus(n, k int) (result []int) {
	queue := []int{}
	for i := 1; i <= n; i++ {
		queue = append(queue, i)
	}

	index := 0
	for len(queue) > 0 {
		index = (index + k - 1) % len(queue)
		result = append(result, queue[index])
		queue = append(queue[:index], queue[index+1:]...)
	}
	return result
}

๐ŸŽจ Python3

# https://www.acmicpc.net/problem/1158
import sys

def josephus(n, k):
    queue = [i for i in range(1, n+1)]
    index = 0
    result = []
    while len(queue) > 0:
        index = (index + k-1) % len(queue)
        result.append(queue[index])
        queue.pop(index)
    return result

if __name__ == "__main__":
    n, k = list(map(int, sys.stdin.readline().split()))
    result = josephus(n, k)
    for i in range(len(result)):
        if i == 0:
            print("<{}".format(result[i]), end='')
        else:
            print(", {}".format(result[i]), end='')
    print(">")
728x90
๋Œ“๊ธ€