约瑟夫问题

本文详细介绍了K12275约瑟夫问题的背景、输入输出样例,通过动态规划方法求解,并给出了完整的C++程序代码,展示了如何计算淘汰顺序和最终赢家。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家好!

不定时更新,题目+解析+评测结果+完整程序,有问题有瑕疵欢迎评论区留言!



1.题目

1. K12275 约瑟夫问题
题目描述

N个人围成一圈,从第一个开始报数,数到M的人出队,然后他的下一位继续从1开始报数,数到M的出队,如此循环直到剩下一个人,求最后剩下的那个人最初是队伍中的第几位。

输入格式

输入玩家人数 N,输入报到哪个数(M)会被淘汰 (M<N,N<100,M,N都是正整数)

输出格式

输出被淘汰人的顺序,以及最终胜利的人(换行输出)

输入输出样例
输入样例1:复制

5 3

输出样例1:复制

the 3 boy out

the 1 boy out

the 5 boy out

the 2 boy out

the 4 boy win

【耗时限制】1000ms 【内存限制】128MB


 2.解析

这是一道十分经典的问题。


1.变量
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
    
}

n:玩家人数。

m:报到哪个数会被淘汰。

now:当前这个人是第几位。

f[]:标记这位玩家是否被淘汰了(false:没淘汰|true:淘汰了)。


2.输入 
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
	scanf("%lld %lld",&n,&m);
}

直接输入n和m。


 3.动态规划
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
	scanf("%lld %lld",&n,&m);
	for(int i=1;i<=n;i++){
		int cnt=0;
		while(cnt<m){
			now++;
			if(now==n+1) now=1;
			if(!f[now]) cnt++;
		}
	}
}

 cnt:报的数。


4. 标记
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
	scanf("%lld %lld",&n,&m);
	for(int i=1;i<=n;i++){
		int cnt=0;
		while(cnt<m){
			now++;
			if(now==n+1) now=1;
			if(!f[now]) cnt++;
		}
		f[now]=true;
	}
}

 实时标记淘汰情况。


4.判断输出
#include<bits/stdc++.h>
using namespace std;
long long n,m,now=0;
bool f[101];
int main()
{
	scanf("%lld %lld",&n,&m);
	for(int i=1;i<=n;i++){
		int cnt=0;
		while(cnt<m){
			now++;
			if(now==n+1) now=1;
			if(!f[now]) cnt++;
		}
		f[now]=true;
		if(i<n) printf("the %lld boy out\n",now);
		else printf("the %lld boy win\n",now);
	}
}

判断输出。


3.评测结果


4.完整程序

#include <bits/stdc++.h>
using namespace std;
int n,k,a[1001];
int fun(string x){
    int sum = 0;
    while(x){
        string
        sum+=x%10;
        x/=10;
    }
    return sum;
}
bool cmp(const int x,const int y){
    if(fun(x)!=fun(y)) return fun(x)>fun(y);
    return x>y;
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    k=a[1];
    sort(a+1,a+n+1,cmp);
    int pm=0;a[n+1]=-1;
    for(int i=1;i<=n;i++){
        if(a[i]!=a[i+1]){
            pm++;
            if(a[i]==k){
                cout<<pm;
                return 0;
            }
        }
    }
    return 0;
}



谢谢大家,给个赞呗!💕💕💕

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值