HDU3089 Josephus again【约瑟夫】【优化】

Josephus again


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 439    Accepted Submission(s): 114

Problem Description
In our Jesephus game, we start with n people numbered 1 to n around a circle, and we eliminated every k remaining person until only one survives. For example, here's the starting configuration for n = 10, k = 2, The elimination order is 2, 4, 6, 8, 10, 3, 7, 1, 9. So 5 survives.The problem: determine the survivor's number , J(n, k).

Input
There are multiple cases, end with EOF
each case have two integer, n, k. (1<= n <= 10^12, 1 <= k <= 1000)
 
Output
each case a line J(n, k)
 
Sample Input
10 2
10 3
 
Sample Output
5
4
 
Source
2009 Multi-University Training Contest 18 - Host by ECNU

Recommend

lcy   |   We have carefully selected several similar problems for you:  3090 3088 3091 3092 3093 


题目大意:有N个人,编号为1~N,按顺时针围成一个圈,每数k个人,就将这个人从圈中消除,

问:最终只留下一个人的编号。

思路:因为N的规模是10^12,所以直接模拟或者是普通递推O(N)都会超时。这里进行一下优

化。具体参考博客:http://www.acmerblog.com/hdu-3089-josephus-again-4869.html

网上已经优化好的递推式为:

num = 0;
for(int i = 2; i <= n; i++)
    num  = (num + m) % i;
当i很大,num和m都比较小的时候(i>>num和m)。num每次增加的其实是m。

而这个增加次数可以算出来。

所以:

一、当num + m >= i时 普通递推。

二、当num + m < i时,设增加次数为x次。满足num + x*m < i + x - 1

第二个之所以是x - 1,是因为num + m < i,num + m + (x-1)*m < i + x -1。

可得:x < (i-num)/(m-1)。x = floor((i-num)/(m-1)) - 1。

这样,num增加了x*m,i增加了x次。

num += x*m,i += x;

但如果i增加的总次数(i+x)>n了,那么最终结果应增加(n-(i-1))*k次,而不是i+x次。


#include<iostream>
#include<algorithm>
#include<math.h>
using namespace std;

int main()
{
    __int64 n,k,ans;
    while(~scanf("%I64d%I64d",&n,&k))
    {
        __int64 num = 0;
        if(k==1)
            num = n-1;
        else if(n == 1)
            num = 0;
        else
        {
            for(__int64 i = 2; i <= n;)
            {
                if(num + k < i)
                {
                    __int64 temp = (i-1-num)%(k-1)?(i-1-num)/(k-1):(i-1-num)/(k-1)-1;
                    if(i + temp > n)
                    {
                        num += (n-(i-1))*k;//n-(i-1)次
                        break;
                    }
                    num += temp*k;
                    i += temp;
                }
                else
                {
                    num = (num + k)%i;
                    ++i;
                }
            }
            num %= n;
        }
        printf("%I64d\n",num+1);
    }

    return 0;
}










  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值