336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.
문제 : https://algospot.com/judge/problem/read/JOSEPHUS
algospot.com :: JOSEPHUS
조세푸스 문제 문제 정보 문제 1세기에 살던 역사학자 조세푸스는 로마와의 전쟁에서 패해 N - 1명의 동료 병사들과 함께 출구가 없는 동굴에 포위당했다고 합니다. 동료 병사들은 로마에 항복하느니 차라리 자살하자고 결의했고, 포위당한 N명의 사람들이 모두 원형으로 둘러선 뒤 순서대로 자살하기로 했습니다. 한 사람이 자살하면, 다음에는 그 사람으로부터 시계 방향으로 K번째 살아 있는 사람이 자살하는 것입니다. 조세푸스의 책에 따르면 조세푸스와 다른 병사 하나
algospot.com
백준 1158 번 조세퍼스 순열 문제와 비슷한 맥락.
2018/03/28 - [PS/백준 문제풀이] - [백준 1158] 조세퍼스 순열 문제
[백준 1158] 조세퍼스 순열 문제
https://www.acmicpc.net/problem/1158 조세퍼스 순열이라고도 하며 요세푸스 순열이라고도 부른다. 해당 순열의 정의는 다음과 같다. 출처는 위키피디아이다. 전산학이나 수학에서 요세푸스 문제(Josephus proble..
hyeonnii.tistory.com
하지만 이번에는 N, K 값이 1000으로 더 작기 때문에 직접 circular linked list를 만들어 풀었다.
#include <iostream>
#include <list>
using namespace std;
int n, k;
struct Node{
int val;
Node *next, *prev;
};
class LinkedList{
private:
int size;
Node *head, *tail;
public:
LinkedList(){
head = NULL;
size = 0;
}
void insertNode(int v){
Node *cur = new Node;
cur->val = v;
size++;
if(!head) head = tail = cur;
else{
cur->prev = tail;
tail->next = cur;
tail = cur;
}
}
int getSize(){
return size;
}
// 머리랑 꼬리 이어줌!
void makeCircular(){
head->prev = tail;
tail->next = head;
}
// 현재 노드 삭제 후 다음 노드 리턴.
Node* deleteNode(Node *cur){
Node* nextNode = cur->next;
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
delete cur;
size--;
return nextNode;
}
Node* getHead(){
return head;
}
// 귀찮아서 남아있는 애 둘 그냥 출력.
void printRemains(Node* cur){
if(cur->val > cur->next->val){
cout << cur->next->val << " " << cur->val << '\n';
}else{
cout << cur->val << " " << cur->next->val << '\n';
}
delete cur->next;
delete cur;
}
};
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--){
LinkedList ll;
cin >> n >> k;
for(int i = 1; i <= n; i++){
ll.insertNode(i);
}
ll.makeCircular();
Node * cur = ll.getHead();
while(ll.getSize() > 2){
cur = ll.deleteNode(cur);
for(int i = 1; i < k; i++)
cur = cur->next;
}
ll.printRemains(cur);
}
return 0;
}
'PS > 알고스팟 문제풀이' 카테고리의 다른 글
[알고스팟 BRACKETS2] Mismatched Brackets (0) | 2019.08.09 |
---|---|
[알고스팟 PASS486] 비밀번호 486 (0) | 2019.08.05 |