约瑟夫环问题

约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以编号1,2,3….n分别表示)围坐在一张圆桌周围。从编号为K的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的人又出列;依此规律重复下去,直到圆桌周围的人全部出列。

思路1:考虑利用链表来解决

#include<list>
#include<cstdlib>
#include<iostream>
using namespace std;
int main(int argc,char* argv[])
{
    int n=0;
    int m=0;
    int count=1;
    loop:
    cout<<" Input the total person\n";
    cin>>n;
    cout<<"Input the choose num\n";
    cin>>m;
    if(n<1||m<1)
    {
        cout<<"Input error! "<<endl;
        goto loop;

    }
    list<int>* table=new list<int>();
    for(int i=1;i<=n;i++)
    {
        table->push_back(i);
    }
    list<int>::iterator iter;
    for(iter=table->begin();table->size()!=1;)
    {
        if(count++==m)
        {
            iter=table->erase(iter);//当报数到m时,将该数从链表中删除
            count=1;//将计数器恢复为1
        }
        else{
            ++iter;//没有点到自己时,继续往下报数
        }
        if(iter==table->end())
        {
            iter=table->begin();//当最后一个人报数时,下一个人自动变为第一个人报数
        }
    }
    cout<<"The last luck person is\n:"<<*table->begin()<<endl;
    system("pause");
    return 0;
}

思路2:利用数学方法设计算法
利用数学方法计算需要归纳推导,虽然程序非常简洁,但是在面试时时间短暂不容易想到,不建议作为该算法的首选。

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值