BOJ-1158号ジョセフス問題(Python)

16255 ワード

質問元:https://www.acmicpc.net/problem/1158
難易度
Silver 5
問題を解く
リンクリストを使用して問題を解決しました.Linkedプロパティを利用して解答しましたが、ノードが削除されるほどサイズが小さくなるので、処理する必要がありますが、処理していないので、ずっとエラーが発生しています!
もっと解きやすい方法もあり、わざとLinkedを習って解きましたが、Pythonのダウンジャケットは参考までに残しておきました.
パスコード
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None


class LinkedList:
    def __init__(self, value):
        self.head = Node(value)

    def append(self, value):
        cur = self.head
        while cur.next is not None:
            cur = cur.next
        cur.next = Node(value)

    def get_node(self, index):
        node = self.head
        count = 0
        while count < index:
            count += 1
            node = node.next

        return node

    def delete_Node(self, index):
        if index == 0:
            ans = self.head.data
            self.head = self.head.next
            return ans
        node = self.get_node(index - 1)
        ans = node.next.data
        node.next = node.next.next
        return ans


if __name__ == '__main__':
    N, K = map(int, input().split())
    ll = LinkedList(1)
    for i in range(2, N + 1):
        ll.append(i)
    arr = []
    idx = K - 1
    while ll.head is not None:
        idx %= N
        arr.append(ll.delete_Node(idx))
        idx += (K - 1)
        N -= 1
    print('<', end='')
    for i in range(len(arr) - 1):
        print(arr[i], end=', ')
    print(arr[len(arr) - 1], end='')
    print('>')
etc

  • N, K = map(int, input().split()) 
    circular_list = [] 
    answer = [] 
    for i in range(N): 
    	circular_list.append(i+1) 
      
    popNum = 0
    
    while len(circular_list) >0: 
        popNum = (popNum + (K-1)) % len(circular_list) 
        popElemnet = circular_list.pop(popNum) 
        answer.append(str(popElemnet)) 
    
    print("<%s>" %(", ".join(answer)))
    ブログ

  • N,K = map(int,input().split())
    arr = [i for i in range(1,N+1)]    # 맨 처음에 원에 앉아있는 사람들
    
    answer = []   # 제거된 사람들을 넣을 배열
    num = 0  # 제거될 사람의 인덱스 번호
    
    for t in range(N):
        num += K-1  
        if num >= len(arr):   # 한바퀴를 돌고 그다음으로 돌아올때를 대비해 값을 나머지로 바꿈  
            num = num%len(arr)
     
        answer.append(str(arr.pop(num)))
    print("<",", ".join(answer)[:],">", sep='')
    ブログ