报数问题(约瑟夫环)

解法一:用数组模拟
#include<iostream>
using namespace std;
int main()
{
 int sign,n,m,i,Loop[100],Count;
 while(cin>>n>>m&&n&&m)
 {
  for(i=0;i<n;i++)
   Loop[i]=i+1;
  sign=0;
  for(i=0;i<n;i++)
  {
   Count=0;
   while(Count<m)
   {
    while(Loop[sign]==0)//越过退出的位置
     sign=(sign+1)%n;
     sign=(sign+1)%n;
     Count++;
   }
  sign--;//实际标号的
  if(sign<0)
   sign=n-1;
  if(i==n-1)
   cout<<Loop[sign]<<endl;
  Loop[sign]=0;
  }
 }
 return 0;
}
复制代码
复制代码
解法二:
//从位置考虑,举例说:
nNum:5  move:2
1 2 3 4 5
3 4 5 1
5 1 3
3 5
3
3在最后一次的pos1位置是0;
倒推,它的位置pos2为(0+2)%2=0;
继续,它的位置pos3为(0+2)%3=2;
pos4=(pos3+2)%4=0;
pos5=(pos4+2)%5=2;
因为实际生活中编号总是从1开始,所以输出加一。

# include<stdio.h>
int main()
{
    int nNum,move,i,pos;
    scanf("%d %d",&nNum,&move);
    pos=0;
    for(i=2;i<=nNum;i++)//倒推
    pos=(pos+move)%i;//把pos看成最后那个人所处的位置
    printf("%d\n",pos+1);
    return 0;
    }
//也可递归:
令f[i]表示i个人报m退出最后胜利者的编号,那最后的结果是f[n].
递推公式:
f[1]=0;
f[i]=(f[i-1]+m)%i; (i>1)
复制代码

 

复制代码
解法三:
//刚看了看链表,就用链表模拟一下
# include<stdio.h>
# include<malloc.h>
# define L sizeof(struct node)
typedef struct node
{
    int num;
    struct node *next;
}SeqList;
SeqList *head,*tail;
void create(int n)//创建链表
{
    SeqList *p;
    int i;
    for(i=1;i<=n;i++)
    {
    p=(SeqList *)malloc(L);
    p->num=i;
    p->next=NULL;
    if(i==1)
    {
        head=p;
    tail=p;
    continue;
    }
    tail->next=p;
    tail=p;
    }
    tail->next=head;
}
void DeletList(int m)//查找报m的人,并删除该节点
{
    SeqList *p,*q;
    int count=0;
    p=tail;
    do
    {
     q=p->next;
      count++;
      if(count%m==0)
      {
         p->next=q->next;
         free(q);
      }
      else p=q;
    }while(p!=p->next);
        head=p;
}
int main()
{
    int n,m;
    while(scanf("%d %d",&n,&m)!=EOF)//n个人,数到m出列
    {
        if(n==1)
            printf("1\n");
        else
        {
        create(n);
        DeletList(m);
        printf("%d\n",head->num);
        }

    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值