swustoj-536 The Josephus Problem

The problem is named after Flavius Josephus, a Jewish historian who participated in and chronicled the Jewish revolt of 66-70C.E. against the Romans. Josephus, as a general, managed to hold the fortress of Jotapata for 47days, but after the fall of the city he took refuge with 40 diehards in a nearby cave. There the rebels voted to perish rather than surrender. Josephus proposed that each man in turn should dispatch his neighbor, the order to be determined by casting lots. Josephus contrived to draw the last lot, and as one of the two surviving men in the cave, he prevailed upon his intended victim to surrender to the Romans. Your task:computint the position of the survivor when there are initially n people.

enter

a Positive Integer n is initially people. n< = 50000

output

the position of the survivor

sample input

6

Sample output

5

Solution: Joseph problem, but k is 2 (I didn't understand the question before and I haven't done QWQ)

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
	int date;
	node *next;
};
intmain()
{
	node *head, *p, *q, *t, *tail;
	int n, k;
    k=2;
	while (scanf("%d %d", &n) != EOF)
	{
		head = NULL;
		for (int i = 1; i <= n; i++)
		{
			p = new node;
			p->date = i;
			p->next = NULL;
			if (head == NULL)
			{
				head = p;
			}
			else
			{
				q->next = p;
			}
			q = p
			tail = q;
		}
		tail->next = head;
		t = head;
		int count = 0;
		while (t->next != t)
		{
			count++;
			if (count == k-1)
			{
				t->next = t->next->next;
				count = 0;
			}
			t = t->next;
		}
		cout << t->date<<endl;
	}
	return 0;
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325668701&siteId=291194637
Recommended