您的位置:首页 > 其它

SDUT 2056 不敢死队问题

2018-03-25 20:20 211 查看

1.问题:

不敢死队问题

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

2.正确代码

#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *next;
};

struct node * create(int n)
{
struct node *head,*p,*tail;

head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
head->data=0;

for(int i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
p->data=i;

tail->next=p;
tail=p;
}

tail->next=head->next;

return head;
}

int kill(struct node *head)
{
int time = 0;

while(1)
{

for(int i=1;i<=4;i++)
{
head=head->next;
}
time++;
if(head->next->da
4000
ta==1)
break;
else
head->next=head->next->next;

}

return time;
}
int main()
{
int num;
struct node *head;

while(scanf("%d",&num)&&num!=0)
{
head=create(num);
printf("%d\n",kill(head));

}

return 0;
}


3.解析:

1.建立环问题注意:首先每次建立节点时要确立好数据,这个必须要保证的;其次,最后的尾部一定要接起来,不要因为图快而丢掉步骤。

2.对循环的处理应该要明确,我们要判断杀掉的数据是否为数字1,但是,我们每次循环结束都是在数字前面,所以要head->next。如果我们在循环判断来处理,那么,我们必然第一个一定是1,为了防止这种情况的发生,我们开始就想,那么head->next->data 必然为1,这样得添加诸多限制条件。直接在循环完后判断,然后退出,这种操作其实很简单的。

while(1)
{

for(int i=1;i<=4;i++)
{
head=head->next;
}
time++;
if(head->next->data==1)
break;
else
head->next=head->next->next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: