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

 

1158번: 요세푸스 문제

첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 5,000)

www.acmicpc.net

 

 

 

 

 

문제

 

요세푸스 문제는 다음과 같다.

1번부터 N번까지 N명의 사람이 원을 이루면서 앉아있고, 양의 정수 K(≤ N)가 주어진다. 이제 순서대로 K번째 사람을 제거한다. 한 사람이 제거되면 남은 사람들로 이루어진 원을 따라 이 과정을 계속해 나간다. 이 과정은 N명의 사람이 모두 제거될 때까지 계속된다. 원에서 사람들이 제거되는 순서를 (N, K)-요세푸스 순열이라고 한다. 예를 들어 (7, 3)-요세푸스 순열은 <3, 6, 2, 7, 5, 1, 4>이다.

N과 K가 주어지면 (N, K)-요세푸스 순열을 구하는 프로그램을 작성하시오.

 

 

 

입력

 

첫째 줄에 N과 K가 빈 칸을 사이에 두고 순서대로 주어진다. (1 ≤ K ≤ N ≤ 5,000)

 

 

 

출력

 

예제와 같이 요세푸스 순열을 출력한다.

 

 

 

 

코드

 

C++

* queue 구현

#include <stdlib.h>
#include <iostream>

using namespace std;

typedef struct _node {
	int i;
	struct _node* next;
} Node;

typedef struct _CLL {
	Node* tail;
	Node* cur;
	Node* before;
	int numOfi;
} CList; // 원형 링크드 리스트

typedef CList List;

void ListInit(List* plist){
	plist->tail=NULL;
	plist->cur=NULL;
	plist->before=NULL;
	plist->numOfi=0;
}

void LInsert(List* plist, int i) {
	Node* newNode=(Node*)malloc(sizeof(Node));
	newNode->i=i;

	if(plist->tail==NULL) {
		plist->tail=newNode;
		newNode->next=newNode;
	} else {
		newNode->next=plist->tail->next;
		plist->tail->next=newNode;
		plist->tail=newNode;
	}
}

int LFirst(List* plist) {
	if(plist->tail==NULL)
		return false;

	plist->before=plist->tail;
	plist->cur=plist->tail->next;

	return true;
}

int LNext(List *plist) {
	if(plist->tail==NULL)
		return false;

	plist->before=plist->cur;
	plist->cur=plist->cur->next;

	return true;
}

int LRemove(List* plist) {
	Node* rpos=plist->cur;
	int ri=rpos->i;

	if(rpos==plist->tail) {
		if(plist->tail==plist->tail->next)
			plist->tail=NULL;
		else
			plist->tail=plist->before;
	}

	plist->before->next=plist->cur->next;
	plist->cur=plist->before;

	free(rpos);
	(plist->numOfi)--;

	return ri;
}

int main() {
	List list;
	ListInit(&list);

	int n, k;
	cin>>n>>k;

	int data=0;

	for(int i=1; i<=n; i++) LInsert(&list, i);
	
	LFirst(&list); // 처음으로 이동
	cout<<"<";
	for(int i=0; i<n; i++){
		for(int j=0; j<k; j++)
			LNext(&list);

		data=LRemove(&list)-1;
		if(data==0) data=n;

		if(i==n-1) cout<<data;
		else cout<<data<<", ";
	}
	cout<<">\n";
	
}

 

파이썬

n, k=map(int,input().split())
arr=[i for i in range(1, n+1)]

ans=list()
idx=0

for i in range(n):
  idx=(idx+k-1)%len(arr)
  ans.append(arr.pop(idx))

print("<", end='')
for a in ans:
  if a==ans[-1]:
    print(a, end=">")
  else:
    print(a, end=', ')
728x90

'알고리즘 > 백준' 카테고리의 다른 글

백준 10430번: 나머지  (0) 2020.03.16
백준 1168번: 요세푸스 문제 2  (0) 2020.03.16
백준 1406번: 에디터  (0) 2020.03.16
백준 11656번: 접미사 배열  (0) 2020.03.16
백준 10824번: 네 수  (0) 2020.03.16