一、热身 [Cloned] R - Joseph

本文探讨了一种约瑟夫问题的变形,其中好人与坏人交替站在圆圈中,目标是找到一个数m,使得所有坏人都在第一个好人被处决前被清除。通过迭代计算确定每个人的位置,直至满足条件。

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

原题:

The Joseph's problem is notoriously known. For those who are not familiar with the original problem: from among n people, numbered 1, 2, . . ., n, standing in circle every mth is going to be executed and only the life of the last remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give us the message about the incident. For example when n = 6 and m = 5 then the people will be executed in the order 5, 4, 6, 2, 3 and 1 will be saved. 

Suppose that there are k good guys and k bad guys. In the circle the first k are good guys and the last k bad guys. You have to determine such minimal m that all the bad guys will be executed before the first good guy. 
题意:

经典的约瑟夫问题,一群人围成一个圈,前k个人是好人,后k个人是坏人,从第一个人开始从1开始报数,每报到n的时候这个人死,然后下一个人继续从1开始报数,直到圈子里剩下的k个人全部都是好人。

题解:

这题之前做过,忘了是poj还是杭电了,看了看以前的代码,发现好像当时测试数据比较少,每输入一个数直接记录,下一次再碰到这个数直接输出结果就行了。

求解方法就是从1穷举,然后加一个数组啊ans[n]表示这一轮死掉的人代号是什么,如果代号小于k,也就是死了好人,就说明报这个数不行,重置报下一个数。

这一轮死的人的代号为ans[i]=(ans[i-1]+m-1)%(n-i+1);就是上一轮的代号加上m-1然后除以剩下的总人数,

这个ans代号的是指每一轮从第一个好人开始数他是第几个,不是最开始的时候这个人在圈里里的序号。

代码:AC

 

 

#include<iostream>
using namespace std;

int main()
{
	int jose[15]={0};
	int k;
	while(cin>>k)
	{
		if(!k)
			break;
		if(jose[k])
		{
			cout<<jose[k]<<endl;
			continue;
		}
		int n=2*k;
		int ans[20]={0};
		int m=1;
		int i;
		for(i=1;i<=k;i++)
		{
			ans[i]=(ans[i-1]+m-1)%(n-i+1);
			if(ans[i]<k)
			{
				i=0; 
				m++;
			}
		}
			jose[k]=m;
			cout<<m<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值