算法基础九:Joseph

Joseph问题

// Joseph's Problem

// input: n,m              -- the number of persons, the inteval between persons

// output:              -- return the reference of last person

 

int josephus0(int n, int m)

{

       if (n == 2) return (m%2) ? 2 : 1;

       int v = (m+josephus0(n-1,m)) % n;

       if (v == 0) v = n;

       return v;

}

int josephus(int n, int m)

{

       if (m == 1) return n;

       if (n == 1) return 1;

       if (m >=n) return josephus0(n,m);

       int l = (n/m)*m;

       int j = josephus(n - (n/m), m);

       if (j <= n-l) return l+j;

       j -= n-l;

       int t = (j/(m-1))*m;

       if ((j % (m-1)) == 0) return t-1;

       return t + (j % (m-1));

}

 

完整代码:

 

#include <iostream>
#include <list>
using  std::cout;
using  std::endl;
using  std::cin;
using  std::list;
 
int  main()
{
     int  total  = 0;
     cout <<  "Please input total number of people : " ;
     cin >> total;
 
     int  number = 0;
     cout <<  "Please input selected number : " ;
     cin >> number;
 
     /* If number = 3
      * f(1) = 0
      * f(2) = 1 = (f(1) + 3) % 2
      * f(3) = 1 = (f(2) + 3) % 3
      * f(4) = 0 = (f(3) + 3) % 4
      * f(5) = 3 = (f(4) + 3) % 5
      * ...
      * f(n) = x = (f(n-1) + 3) % n
      * */
 
     int  last = 0;  // f(1) = 0
     for ( int  i = 2; i <= total; ++i)
     {
         last = (last + number) % i;
     }
     cout <<  "The last one is : "  << last + 1 << endl;
 
     return  0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值