“顶嵌杯”--初赛第3题分析

小孩报数问题

有N个小孩围成一圈,给他们从1开始依次编号,现指定从第W个开始报数,报到第S个时,该小孩出列,然后从下一个小孩开始报数,仍是报到S个出列,如此重复下去,直到所有的小孩都出列(总人数不足S个时将循环报数),求小孩出列的顺序。
输入:
       第一行输入小孩的人数N(N<=64)
接下来每行输入一个小孩的名字(人名不超过15个字符)
最后一行输入W,S(W<N),用逗号”,”间隔
输出:
       按人名输出小孩按顺序出列的顺序,每行输出一个人名
样例输入:
5
Xiaoming
Xiaohua
Xiaowang
Zhangsan
Lisi
2,3
样例输出:
Zhangsan
Xiaohua
Xiaoming
Xiaowang
Lisi
提示:
可用链表来实现
考察重点:约瑟夫算法、链表
参考代码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#define MAX_NAME_LEN 16
typedef struct _child {
    char name[MAX_NAME_LEN];
    struct _child * pre;
    struct _child * next;
} Child;
Child* init(Child* init_child) {
    if (init_child == NULL) {
        return;
    }
    init_child->pre = init_child;
    init_child->next = init_child;
    return init_child;
}
void append(Child* list, Child* new_child) {
    if (list == NULL || new_child == NULL) {
        return;
    } 
    new_child->pre = list->pre;
    new_child->next = list;
    list->pre->next = new_child;
    list->pre = new_child;
}
void select_child(Child* list, int begin, int sel, int count) {
    int i;
    // selecting begins from the 'sel'th child
    for (i=1; i<begin; i++) {
        list = list->next;
    }
    while (count--) {
        for (i=1; i<sel; i++) {
            list = list->next;
        }
        printf("%s/n", list->name);
        list->pre->next = list->next;
        list->next->pre = list->pre;
        list = list->next;
    }
}
int main()
{
    int count;
    scanf("%d", &count);  
    Child* p = (Child*)malloc(sizeof(Child) * count);
    memset(p, 0, sizeof(Child) * count);
    scanf("%s", p->name);
    Child* list = init(p);
    int i;
    for (i=1; i<count; i++) {
        Child* new_child = (Child*)(p+i);
        scanf("%s", new_child->name);
        append(list, new_child);
    }  
    int begin, sel;
    scanf("%d,%d", &begin, &sel);
    select_child(list, begin, sel, count);
    free(p);
    return 0;
}

文章来源:http://top-e.org/student/html/509.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值