josephus约瑟夫环问题变种 核心:求模运算 移动

欢迎提出不同意见:QQ 1423173783  邮箱:1423173783@qq.com

//代码解决的问题: 有length个人编号为1,2,,,,,length围成一桌,从编号为start的人开始报数,编号为start的人报1,编号为start+1的人报2,依次类推报到standard的人被击中一次,
//当某个人被击中的次数达到hittimes次则这个人出列被淘汰,下一人接着报1,如此循环直到剩余一个胜者。程序会依次输出出列人的编号。
//代码接口不友好,不但要依次输入 length  start  standard  hittimes 且在输入这些值之前要即运行程序前要找到main函数中结构体声明,并把结构体数组person【】的长度改为您即将要输入的length。
//但效率高。
#include <stdio.h>
#include "malloc.h"
#include<iomanip>
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
 int s1,remove=0;
 int length,start,standard,hittimes;
   time_t nowtime1, nowtime2;
 ofstream out_stream;
 out_stream.open("d:\\c++\\josephus 9\\outfile.txt");
    nowtime1=time(NULL); 
 out_stream<<nowtime1<<endl;
 cout<<"please input the values(<100) of length  start  standard hittimes"<<endl;
 cin>>length>>start>>standard>>hittimes;
 out_stream<<"length="<<length<<" "<<"start="<<start<<" "<<"standard="<<standard<<" "<<"hittimes="<<hittimes<<endl;
 struct {
  int num;
  int times;
 }person[16];
 for(int i=0;i<length;i++)
 {
  person[i].num=i+1;
  person[i].times=0;
 };
 s1=start-1;
 for(int i=length;i>0;i--)
 {
  while(1)
  {
      s1=(s1+standard-1)%i;
      person[s1].times++;
      if( person[s1].times==hittimes)
       {
                 out_stream<<setw(8)<<person[s1].num<<" ";
           remove++;
     if(remove%10==0)  out_stream<<endl;
     for(int j=s1;j<i;j++)
      person[j]=person[j+1];
     break;
       }
   else
   {s1+=1;
    if(s1==i)   s1=0;
   }
  }
 }
 out_stream<<endl;
 nowtime2=time(NULL);
 out_stream<<nowtime2<<endl;
 out_stream<<nowtime2-nowtime1<<endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值