不敢死队问题

Problem Description

说到“敢死队”,大家不要以为我来介绍电影了,因为数据结构里真有这么道程序设计题目,原题如下:

 

有M个敢死队员要炸掉敌人的一个碉堡,谁都不想去,排长决定用轮回数数的办法来决定哪个战士去执行任务。如果前一个战士没完成任务,则要再派一个战士上去。现给每个战士编一个号,大家围坐成一圈,随便从某一个战士开始计数,当数到5时,对应的战士就去执行任务,且此战士不再参加下一轮计数。如果此战士没完成任务,再从下一个战士开始数数,被数到第5时,此战士接着去执行任务。以此类推,直到任务完成为止。

 

这题本来就叫“敢死队”。“谁都不想去”,就这一句我觉得这个问题也只能叫“不敢死队问题”。今天大家就要完成这道不敢死队问题。我们假设排长是1号,按照上面介绍,从一号开始数,数到5的那名战士去执行任务,那么排长是第几个去执行任务的?

Input

输入包括多试数据,每行一个整数M(0<=M<=10000)(敢死队人数),若M==0,输入结束,不做处理。

 

Output

输出一个整数n,代表排长是第n个去执行任务。

Example Input
9
6
223
0
Example Output
2
6
132
 
 
 
 
 
 
 
 
 
 
 
 
#include <stdio.h>
#include <stdlib.h>
struct die
{
    int num;
    struct die *next;
}*p,*head,*tail,*q;
struct die *creat(int n)
{
    int i;
    p=(struct die *)malloc(sizeof(struct die));
    p->num=1;
    p->next=NULL;
    head=p;
    tail=p;
    for(i=2;i<=n;i++)
    {
        p=(struct die *)malloc(sizeof(struct die));
        p->num=i;
        tail->next=p;
        tail=p;
        p->next=NULL;
    }
    tail->next=head;
    return head;
}
int sel(struct die *head,int n)
{
    int num=0;
    int count=0;
    q=head;
    while(q->next!=head)
    {
       q=q->next;
    }
    while(q->num!=1)
    {
        p=q->next;
        num++;
        if(num%5==0)
        {
            q->next=p->next;
           // printf("%d",p->num);
            free(p);
            count++;
        }
        else
            q=p;
    }
    return count;
}
int main()
{
    int n,m,g;
    while(~scanf("%d",&n)&&n)
    {
        head=creat(n);
      g=sel(head,n);
    printf("%d\n",g);
    }
}








#include <stdio.h>
#include <stdlib.h>
struct node
{
    int num;
    struct node *next;
}*head,*tail,*p,*q;
void die(int n)
{
    int i,count,s;
     head=(struct node *)malloc(sizeof(struct node));
     head->next=NULL;
     head->num=1;
     tail=head;
     for(i=2;i<=n;i++)
     {
         p=(struct node *)malloc(sizeof(struct node));
         p->next=NULL;
         p->num=i;
         tail->next=p;
         tail=p;
         //tail->next=NULL;
     }
     tail->next=head;
     q=head;
     s=1;count=1;
     while(q->num!=q->next->num)
     {
         for(i=1;i<4;i++)
         {
             q=q->next;
         }
         if(q->next->num!=1)
         {
            q->next=q->next->next;
            q=q->next;
            count++;
         }
         else
         {
             printf("%d\n",count);
             s=0;
             break;
         }
     }
     if(s==1)
            printf("%d\n",n);
}
int main()
{
    int n;
    while(~scanf("%d",&n)&&n)
    {
        die(n);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值