约瑟夫问题 分类: 链表 2015-06-08 08:14 26人阅读 评论(0) 收藏

约瑟夫问题

TimeLimit: 1000MS Memory limit: 65536K

题目描述

n个人想玩残酷的死亡游戏,游戏规则如下:

n个人进行编号,分别从1n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。

请输出最后一个人的编号。

输入

输入nm值。

输出

输出胜利者的编号。

示例输入

53

示例输出

4

#include <bits/stdc++.h>
#define RR freopen("input.txt","r",stdin)
#define WW freopen("output.txt","w",stdout)

using namespace std;

const int mod=10007;

struct node
{
    int data;
    node *next;
};
int main()
{
    int n,m;
    node *head,*p,*tail,*q;
    head=new node;
    head->next=NULL;
    tail=head;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        p=new node;
        p->next=NULL;
        p->data=i;
        tail->next=p;
        tail=p;
    }
    tail->next=head->next;
    int ans=1;
    q=head;
    p=head->next;
    while(n!=1)
    {
        if(ans%m)
        {
            p=p->next;
            q=q->next;

        }
        else
        {
            q->next=p->next;
            free(p);
            p=q->next;
            n--;
        }
        ans++;
    }
    cout<<p->data<<endl;
    return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/juechen/p/4722058.html