NOJ 1018 选太子

2016.12.27

【问题描述】
描述
某皇帝有2m个儿子,现在要从中选出一个做太子,皇帝不知道该把那一个皇子立为太子,于是决定用下面的方法来选出太子,设每个太子的编号分别1、2、3、…、2m,按顺时针方向站成一个圆圈,现在从1号太子开始按顺时针方向数,数到第n个人,把他淘汰出局,然后从他的下一个人开始上述过程,当第m个人被淘汰时,转变方向继续从1开始数,重复上述过程,最后剩下的皇子将被立为太子。现在请你写一个程序,计算出几号皇子将被立为太子。

输入
输入两个正整数m n
输出
输出太子的编号

输入样例
3 2

输出样例
1

【解题思路】
双向链表模拟筛选过程

【代码实现】

#include <stdio.h>
#include <stdlib.h>

int m, n, cnt, cntn, cntm;
struct node 
{
    int num;
    struct node * next, * pre;
};

struct node * create();
void del(struct node *);

int main(void)
{
    int d = 1;
    struct node * head, * current, *t;

    scanf("%d%d", &m, &n);

    cnt = 2 * m;
    cntn = cntm = 0;
    head = create();

    current = head;
    while (cnt > 1)
    {
        cntn++;
        if (cntn == n)
        {
            cntn = 0;
            cntm++;
            cnt--;
            if (cntm == m)
            {
                d = -d;
                cntm = 0;
            }
            if (d == 1)
                t = current->pre;
            else
                t = current->next;
            del(current);
            current = t;
        }
        if (d == 1)
            current = current->next;
        else
            current = current->pre;
    }

    printf("%d\n", current->num);

    return 0;
}

struct node * create()
{
    int i;
    struct node * head, * current, * prev;

    head = NULL;
    for (i = 1; i <= 2*m; ++i)
    {
        current = (struct node *) malloc(sizeof(struct node));
        if (head == NULL)
        {
            head = current;
            prev = head;
        }
        else
            prev->next = current;
        current->num = i;
        current->next = head;
        current->pre = prev;
        prev = current;
    }
    head->pre = current;
}

void del(struct node * c)
{
    struct node * tt;

    c = c->pre;
    tt = c->next->next;
    free(c->next);
    tt->pre = c;
    c->next = tt;
}

【心得体会】
掌握双向链表的基本使用

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值