P1996 Joseph Problem (Logu)

Original title portal

Insert picture description here
Idea: First define an integer array to represent n people, and then continue to traverse the array. The counts that have not been kicked out add 1, and the counts that are kicked out are assigned to -1, and the count starts again, and the kicked out people increase by 1. After traversing the array once, the traversal starts again until the number of people kicked out equals the total number of people. This question is about the linked list in the data structure. I am here to simulate the whole process directly, but it can also be done with a linked list.

Code reference

#include<bits/stdc++.h>
using namespace std;
const int MAXN = 101;
int n,m,a[MAXN],num,t;//num用来计数,t代表已经被踢出的人数
int main()
{
    
    
    cin>>n>>m;
    //给数组赋值
	for(int i=1;i<=n;i++)
        a[i]=i;
    //遍历数组
	for(int i=1;;i++)
	{
    
    
	    //假如还没被踢出去,则计数+1
		if(a[i]!=-1)
            num++;
		if(num==m && a[i]!=-1)
		{
    
    
            cout<<a[i]<<" ";
            a[i]=-1;//被踢出后则元素重新赋值
            t++;
            num=0;//计数重新开始
		}
		//遍历完一次后重新开始
		if(i==n)
            i=0;
		if(t==n)
            break;
	}
    return 0;
}

Guess you like

Origin blog.csdn.net/Bertil/article/details/106795326