约瑟夫环问题

来源:互联网 发布:淘宝卖家和买家都被骗 编辑:程序博客网 时间:2024/06/03 19:36

约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知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
原创粉丝点击