求助
本帖最后由 sara_est_sarah 于 2021-10-6 20:24 编辑系统说我答案正确,但有presentation error...
真找不到,希望各位能幫忙看看,谢谢。
#include <iostream>
using namespace std;
class node
{
public:
int data;
node*next;
};
int main()
{
int n,m,i;
char a;
int answer;
int count=0;
struct node *head,*tail,*p,*q;
head=(struct node*)malloc(sizeof(struct node));
head->data=-1;
head->next=NULL;
cin>>n>>m;
tail=head;
for(i=0;i<n;i++)
{
p=(struct node*)malloc(sizeof(struct node));
p->data=i+1;
tail->next=p;
p->next=head->next;
tail=p;
}
p=head->next;
q=tail;
i=1;
while(p!=q)
{
if(i==m){
q->next=q->next->next;
int j=p->data;
cout<<j<<" ";
free(p);
p=q->next;
i=1;
}
else
{
q=p;
p=p->next;
i++;
}
}
answer=p->data;
count++;
free(p);
head->next=NULL;
for (i=0;i<count;i++){
cout<<answer;
}
free(head);
return 0;
}
这是问题 (Josephus Problem)
n individuals labeled from 1 to n form a circle, which means the next person of the n-th person
is the first person. Counting begins at the first person, and the m-th person counted will go out.
Then the counting restart at the next person of the one who went out, and still the m-th person
counted will go out. Repeat the counting until all of the people have gone out.
In this problem, given n and m, please show the order they went out.
Input
A single line containing two integers n and m separated by a space.
Output
Print n integers in a single line denoting the labels of these n persons and indicating the order
they went out. Please separate each two of these integers by a single space.
Constraint
1≤n,m≤10^4
页:
[1]