【11.6 测试】约瑟夫问题

 YJC 很喜欢玩游戏,今天他决定和朋友们玩约瑟夫游戏。

约瑟夫游戏的规则是这样的:n个人围成一圈,从1 号开始依次报数,当报到m 时,报1、2、…、m-1 的人出局,下一个人接着从1 开始报,保证(n-1)是(m-1)的倍数。最后剩的一个人获胜。

YJC 很想赢得游戏,但他太笨了,他想让你帮他算出自己应该站在哪个位置上。

【输入格式】
  第一行包含两个整数n 和m,表示人数与数出的人数。

【输出格式】
  输出一行,包含一个整数,表示站在几号位置上能获得胜利。

【输入样例】
10 10

【输出样例】
10

【数据范围】
对于30%的数据,2 ≤ n ≤ 1000。
对于70%的数据,2 ≤ n ≤ 1000000。
对于100%的数据,2 ≤ m ≤ n ≤ 2^63-1

题解:

代码:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
ll n,m;
int main(){
    freopen("joseph.in","r",stdin);
    freopen("joseph.out","w",stdout);
    scanf("%lld %lld",&n,&m);
    //ll s1=(n-1)/(m-1);
    if(n==m) {
        printf("%lld",n);
        return 0;
    }
    //ll s2=n%m;
    //ll ans=((s1+s2)%m+1)*m;
    //ll ans=(m-s2)*m;
    ll tot=1;
    while(tot<n) tot*=m;
    tot/=m;
    //printf("%lld ",tot);
    ll ans=(n-tot)/(m-1)*m;
    printf("%lld
",ans);
    //printf("%lld",abs((((n-1)/(m-1))-2)*m));
}
原文地址:https://www.cnblogs.com/wuhu-JJJ/p/11805400.html