約瑟夫環問題C++實現
阿新 • • 發佈:2018-12-20
題目就不說了,學過演算法或者看過一些程式設計思維故事的人應該都有了解這個經典的問題。這裡直接看程式碼和執行結果。
#include <bits/stdc++.h>
using namespace std;
int n,m;
int main()
{
while(cin>>n>>m)
{
int man[n]= {0};
int count=1,i=0,pos=-1,alive=0;
while(count<=n)
{
do
{
pos=(pos+1)%n;
if(!man[pos])
i++;
if(i==m)
{
i=0;
break;
}
}
while(1);
man[pos]=count;
count++;
}
cout<< "最初位置--約瑟夫環位置\n";
for(i=0; i<n; i++)
{
cout<<i+1<<"-"<<man[i]<<" ";
if(i!=0&&i%10==0)
cout<<endl;
}
cout<<"輸入剩下的人數?"<<endl;
cin>>alive;
alive=n-alive;
for (i=0; i<n; i++)
{
if(man[i]>alive)
cout<<"初始序號:"<<i+1<<" 約瑟夫環序號:"<<man[i]<<endl;
}
}
return 0;
}