ACM준비/algospot

JOSEPHUS

조규현15 2015. 9. 10. 17:50
반응형

https://algospot.com/judge/problem/read/JOSEPHUS

 

algospot.com :: JOSEPHUS

조세푸스 문제 문제 정보 문제 1세기에 살던 역사학자 조세푸스는 로마와의 전쟁에서 패해 N - 1명의 동료 병사들과 함께 출구가 없는 동굴에 포위당했다고 합니다. 동료 병사들은 로마에 항복하

algospot.com

단순 리스트 문제임.

처음엔 리스트 함수들을 자세히 정의해서 제출하니 시간초과됨.

다시 단순하게 변경하여 제출해서 통과됨.

다만, 너무 단순하게 생각해서 시간이 꽤나 나오는게 아쉬움.

다음에 다시 도전해서 나이스하게 변경하면 좋겠음.

typedef struct node{
	int value;
	node *prev;
	node *next;
}queue;

queue *Head;
int N;

node * deleteNode(node *head, int index)
{
	--N;
	node *prev, *current = head;

	for (; index > 0; index--)
	{
		current = current->next;
	}
	prev = current->prev;

	prev->next = current->next;
	current->next->prev = prev;

	free(current);

	return prev->next;
}
node * makeNode(node *Current, int index)
{
	node *temp = (node*)malloc(sizeof(node));

	temp->value = index;
	temp->next = NULL;
	temp->prev = NULL;

	if (Current != NULL){
		Current->next = temp;
		temp->prev = Current;
	}
	else
		Head = temp;

	return temp;
}
int main()
{
	int C;
	for (scanf("%d", &C); C > 0; C--)
	{
		int K;
		scanf("%d %d", &N, &K);
		
		node * temp = Head = NULL;
		for (int i = 1; i <= N; i++)
			temp = makeNode(temp, i);
		temp->next = Head;
		Head->prev = temp;

		temp = deleteNode(Head, 0);
		while (N > 2)
			temp = deleteNode(temp, K - 1);
		
		int a = temp->value;
		int b = temp->next->value;

		printf("%d %d\n", (a < b) ? a : b, (a < b) ? b : a);

		free(temp->next);
		free(temp);
	}
	return 0;
}
반응형

'ACM준비 > algospot' 카테고리의 다른 글

JEONGLIBE  (0) 2015.09.11
IMGFILTER  (0) 2015.09.10
FIXPAREN  (0) 2015.09.10
POTION  (0) 2015.09.10
COINS  (0) 2015.09.09