Several Solutions to the Problem of Joseph Ring

problem

There are n people in a circle, from 1 to m to report the number in turn, and the people who report to m are listed, asking for related questions.
Note: all are a set of test samples!!!

method 1:

#include<iostream>
using namespace std;


//依次输出出列的人的编号 
int main()
{
    
    
	int m,n,p,i=0;
	cin>>n>>m;
	for(i=1;i<=n;i++)
	{
    
    
		p=i*m;
		while(p>n)
		    p=p-n+(p-n-1)/(m-1);
		cout<<p<<" ";
	}
	return 0;
 }
 
 /*//输出最后出列的人的编号 
 int main()
{
	int m,n,p,i=0;
	cin>>n>>m;
	i=n;
	p=i*m;
	while(p>n)
	    p=p-n+(p-n-1)/(m-1);
	cout<<p;
	return 0;
 }*/

Method 2:

#include<iostream>
using namespace std;

//输出最后出列的人的编号
int main()
{
    
    
	int n,m,i;
    cin>>n>>m;
	{
    
    
		int p=0;
		for(i=2;i<=n;i++)
		{
    
    
			p=(p+m)%i;
		}
		cout<<p+1; 
	} 
	return 0;
 } 

Method 3: simulation process

#include<stdio.h>

int main()
{
    
    
	int n,m;//n个人玩游戏,报数到m出圈
	int s;//s表示出圈人数
	int c;//表示当前报数的人的编号
	int k;//k表示当前此人报的数为k
	int a[200];
	while((scanf("%d %d",&n,&m))!=EOF)
	{
    
    
		s=c=k=0;
        int a[200]={
    
    0};
		while(s!=n)
		{
    
    
		    c++;
		    if(c>n)
			    c=1;
		    if(a[c]==0)//表示该人还在圈内,应该继续报数
			{
    
    
			    k++;
		        if(k==m)//当前编号为c的人所报数为k,且要出圈
		        {
    
    
			        a[c]=1;
			        s++;
			        k=0;//从头开始报数
			        //***********//对该部分内容修改,可解决不同类型题目
			        if(s==n)
			            break;
			        printf("%d\n",c);
			        //***********//
		        }
	    	}
	    }
	}
	return 0;
 }

Guess you like

Origin blog.csdn.net/weixin_51800059/article/details/111562967