sara_est_sarah 发表于 2021-10-6 20:00:24

救助

本帖最后由 sara_est_sarah 于 2021-10-6 20:10 编辑

系統说答案是正確的,但presentation error ...
为什么。。。谢谢。

#include <iostream>

using namespace std;
class node
{
    public:
    int data;
    struct 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;
}

sara_est_sarah 发表于 2021-10-6 20:10:01

Question: (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,n≤10^4
页: [1]
查看完整版本: 救助