版权声明:本人原创文章若需转载请标明出处和作者!沙 https://blog.csdn.net/weixin_44143702/article/details/87862770
不敢死队问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
说到“敢死队”,大家不要以为我来介绍电影了,因为数据结构里真有这么道程序设计题目,原题如下:
有M个敢死队员要炸掉敌人的一个碉堡,谁都不想去,排长决定用轮回数数的办法来决定哪个战士去执行任务。如果前一个战士没完成任务,则要再派一个战士上去。现给每个战士编一个号,大家围坐成一圈,随便从某一个战士开始计数,当数到5时,对应的战士就去执行任务,且此战士不再参加下一轮计数。如果此战士没完成任务,再从下一个战士开始数数,被数到第5时,此战士接着去执行任务。以此类推,直到任务完成为止。
这题本来就叫“敢死队”。“谁都不想去”,就这一句我觉得这个问题也只能叫“不敢死队问题”。今天大家就要完成这道不敢死队问题。我们假设排长是1号,按照上面介绍,从一号开始数,数到5的那名战士去执行任务,那么排长是第几个去执行任务的?
Input
输入包括多试数据,每行一个整数M(0<=M<=10000)(敢死队人数),若M==0,输入结束,不做处理。
Output
输出一个整数n,代表排长是第n个去执行任务。
Sample Input
9
6
223
0
Sample Output
2
6
132
注意:
1. 排长是最后一个去执行任务的特殊情况!
2. 若将 count 定义为全局变量时,记得每次调用 game 函数时要重置 count !!!
3. game函数中判断 number = 1 时, if的摆放位置很重要
4. game函数中判断 i = m 时,else一定要加上,否则是错的
#include <stdio.h>
#include <stdlib.h>
struct node
{
int number;
struct node *next;
};
struct node * Circular_Linked_List(int);
int game(struct node *, int);
int main()
{
int n, m;
struct node *head;
m = 5;
while(~scanf("%d", &n))
{
if(n == 0) break;
head = Circular_Linked_List(n);
printf("%d\n", game(head, m));
}
return 0;
}
struct node * Circular_Linked_List(int n)
{///创建循环链表
int i;
struct node *head, *tail, *p;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
tail = head;
for(i = 1; i <= n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
p->number = i;
tail->next = p;
tail = p;
}
tail->next = head->next;
return head;
};
int game(struct node *head, int m)
{///在链表中循环,直到剩下一个结点元素时结束循环,并将该结点的编号返回
int i, count;
struct node *tail, *q;///游动指针及其前驱指针
q = head;
tail = q->next;
i = 1;
while(q->next != head->next) q = q->next;
///遍历一遍链表,令 q 指向尾结点,在 tail 前面
count = 0;///注意清零!!!找了一个小时的错误居然是没清零
while(tail->next != tail)
{///循环链表,当指针指向自己时,即只剩下一个元素时
if(i == m)///注意此处不要习惯性把 m 写成 样例的数字了!!!
{///当计数到 m 时,删除该结点
count++;///每当数到 m 时,计数变量加一
if(tail->number == 1)///注意这个 if 的位置,不能放在count前面
{
return count;
}
q->next = tail->next;
free(tail);
tail = q->next;
i = 1;
}
else///这个 else 必须要加上!!!否则会出错
{///会导致指针 tail 和计数变量 i 不对应
q = q->next;
tail = tail->next;
i++;///计数变量必须和指针 tail 对应,要动一起动!
}///这段程序不能放在 if 前面,否则指针开始时就后移
}///会漏判一次,导致错误
///如果从循环中出来还未轮到排长,则排长是最后一人,即第 n 个人
///但是此函数中没有传入 n ,自然也无法返回 n
///但是此时 n = count + 1,所以:
count++;
return count;
}