The Josephus Problem
阿新 • • 發佈:2018-11-03
The Josephus Problem
1000(ms)
65535(kb)
834 / 2034
The problem is named after Flavius Josephus, a Jewish historian whoparticipated in and chronicled the Jewish revolt of 66-70C.E.against the Romans. Josephus, as a general, managed to hold thefortress of Jotapata for 47days, but after the fall of the city hetook refuge with 40 diehards in a nearby cave. There the rebelsvoted to perish rather than surrender. Josephus proposed that eachman in turn should dispatch his neighbor, the order to bedetermined by casting lots. Josephus contrived to draw the lastlot, and as one of the two surviving men in the cave, he prevailedupon his intended victim to surrender to the Romans. Yourtask:computint the position of the survivor when there areinitially n people.
@淺夏沫若.code:
#include
using namespace std; int main()
{
int n = 0;
int flag = 0;
int counter = 0;
int a[50001] = {0};
cin >> n;
while (1)
{
for (int i = 1; i <= n;i++)
{
if (flag ==1&&a[i]==0)
{
a[i]= 1;
counter= counter + 1;
flag= 0;
if(counter == n - 1)
break;
}
else if (flag== 0 && a[i] == 0)
{
flag= 1;
}
}
if (counter == n - 1)
break;
}
for(int i=1;i<=n;i++)
if (a[i] == 0)
{
cout <<i << endl;
}
return 0;
}
輸入
a Positive Integer n is initially people. n< = 50000
輸出
the position of the survivor
樣例輸入
6
樣例輸出
5
@淺夏沫若.code:
#include
using namespace std; int main()
{
int n = 0;
int flag = 0;
int counter = 0;
int a[50001] = {0};
cin >> n;
while (1)
{
for (int i = 1; i <= n;i++)
{
if (flag ==1&&a[i]==0)
{
a[i]= 1;
counter= counter + 1;
flag= 0;
if(counter == n - 1)
break;
}
else if (flag== 0 && a[i] == 0)
{
flag= 1;
}
}
if (counter == n - 1)
break;
}
for(int i=1;i<=n;i++)
if (a[i] == 0)
{
cout <<i << endl;
}
return 0;
}