【问题描述】
在计算机科学和数学中,约瑟夫斯问题(或约瑟夫斯置换)是一个与某个计数游戏相关的理论问题。
接下来我们将解决这样一个问题:
犯人围成一圈等待处决。计数从圆中的指定点开始(默认为第一个人),并沿指定方向(顺时针方向)围绕圆进行,并对每一个人进行编号,依次为:1,2,3....。跳过指定数量的人员后,下一个人员将被处死。对剩下的人重复这个过程,下一个人开始,朝同一方向走,跳过相同数量的人,直到只剩下一个人,然后该名犯人被释放。
【输入,输出】
已知条件:犯人总人数,起始点,计数方向,跳过人数。
所求结果:剩下的最后一个人的编号
输入:m n(如:30 6表示一共30人,每次第7个被处刑)
输出 : 最后剩下的人的编号
【样例】
1#:
输入:5 3↵ 输出: The lucky person is no:1↵
2#:
输入:5 1↵ 输出:The lucky person is no:3↵
【问题分析】
从问题中不难发现,这个题目隐含许多我们要去解决的问题以及得到的信息:
- 每个人的编号
- 下一个人的编号
- 如何在只剩最后一个人时停止
- 如何从最后一个人返回第一个人
- 如何将跳过已被执行的人,进行计数
这都是我们要去分析的,很显然,这个题利用链表很好实现,但我分享的两种方法将不会使用链表。
【代码实现】
1.利用结构:
/*Josephus problem*/
#include <stdio.h>
struct person {
int nextp;
int NO;
} link[100];
int main()
{
int num, target;
scanf("%d %d", &num, &target);
//将target赋值
target = target + 1;
int count = 0;
int death = 0;
/*先建立一个环结构*/
for (int i = 1; i <= num ; i++) {
if ( i == num) //如果为最后一个人,那么其下一个人为第一个人
link[i].nextp = 1;
else
link[i].nextp = i + 1; //反之,则为下一个人
link[i].NO = i; //给犯人编号
}
for (int j = 1 ; j <= num ;) {
/*剩下最后一人停止*/
if (death == num - 1)
break;
/*从第一个人判断,并计数*/
if (link[j].NO != 0) {
count++;
}
/*一旦满足要求,令当前编号为0,计数器清零*/
if (count == target) {
link[j].NO = 0;
count = 0;
death++;
}
/*判断下一轮的开始元素*/
if (link[j].nextp == 1)
j = 1;
else
j = link[j].nextp;
}
/*输出最后一个人*/
for (int k = 1 ; k <= num ; k++)
if (link[k].NO != 0) {
printf("The lucky person is no:%d\n", k);
return 0;
}
}
2.只利用循环
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int m, n;
scanf("%d %d", &m, &n);
char a[10000];
memset(a, 0, 10000);
for (int i = 1; i <= m; i++) {
a[i] = 1;
}
int die = 0;
int now_position = 1;
int count = 0;
while (1) {
if (die == m - 1)
break;
if (now_position + 1 <= m) {
now_position ++;
} else {
now_position = 1;
}
if (a[now_position] != 0) {
count ++;
} else {
continue;
}
if (count == n) {
a[now_position] = 0;
die++;
count = -1;
}
}
for (int i = 1; i <= m; i++) {
if (a[i] == 1) {
printf("The lucky person is no:%d\n", i);
return 0;
}
}
}