约瑟夫问题

约瑟夫问题的提法:

       n个人围成一个圆圈,首先第1个人从1开始一个人一个人顺时针报数, 报到第m个人,令其出列。然后再从下一个人开始,从1顺时针报数,报到第m个人,再令其出列,…,如此下去, 直到圆圈中只剩一个人为止。此人即为优胜者。

#include <stdio.h>
#include <malloc.h>

struct node{
    int data;
    struct node *next;
};

int main()
{
    int numOfPeople;    // 参加游戏的人数
    int countsFirst;    // 第一个开始报数的人
    int key;    // 报数的关键数字
    int i;    // 计数变量

    struct node *p, *tmp, *head;

    printf("Please enter the number of people: ");
    scanf(" %d", &numOfPeople);
    printf("Please enter the number of the person who counts first: ");
    scanf(" %d", &countsFirst);
    printf("Please enter the key number: ");
    scanf(" %d", &key);

    head = (struct node*)malloc(sizeof(struct node));
    p = head;
    for (i = 1; i < numOfPeople; i++)
    {
	// 定义所有人的编号
        p->data = i;
        p->next = (struct node*)malloc(sizeof(struct node));
        p = p->next;
    }
	// 连接成环
    p->data = numOfPeople;
    p->next = head;
    p = head;

    while (p->data != p->next->data)    // 剩下的最后一位是自己首尾相连的
    {
        while(p->data != countsFirst)
            p = p->next;
        if (1 == key)    // 关键数字是1的情况
        {
            for(i = 1; i < numOfPeople; i++)
            {
                printf("%d out!\n", p->data);
                p = p->next;
            }
            printf("%d win! ", p->data);    // 最后一位胜利
            return 0;
        }
        else
        {
            for (i = 1; i < key - 1; i++)
                p = p->next;
        }
        tmp = p->next;
        printf("%d out!\n", tmp->data);
        countsFirst = tmp->next->data;
        p->next = tmp->next;
    }

    printf("%d win! ", p->data);
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值