POJ 1781 In Danger 约瑟夫环(log(m))


#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

//编号从0,1,2,···n-1
//n为人数,m为出圈步长,s为起使报数位置(起始位置不一定要出圈)
int Josephus ( int n, int m, int s )
{
    if ( m == 1 )
        return ( s + n - 1 ) % n;

    for ( int i = 2; i <= n; i++ )
    {
        s = ( s + m ) % i;
        //if ( i == n ) break;

        if ( s + m < i )
        {
            int x = (i-s) / (m-1); // s + m * x <= i + x;
            if ( i + x < n )
            {
                i = i + x;
                s = ( s + m * x ) % i;
            }
            else { s = (s + m * (n-i)) % n; break; }
        }
    }
    return s; //返回最后一人的位置
}

int Jose ( int n, int m, int s )
{
    for ( int i = 2; i <= n; i++ )
        s = ( s + m ) % i;
    return s;
}

int main()
{
    char str[10];
    while ( scanf("%s",str) )
    {
        int t0 = str[0] - '0';
        int t1 = str[1] - '0';
        int t3 = str[3] - '0';
        if ( t0 + t1 + t3 == 0 ) break;
        int num = 1;
        while ( t3-- ) num *= 10;
        num = t0 * num * 10 + t1 * num;
        //printf("num = %d\n",num);
        int res = Josephus ( num, 2, 0 );
        //int res1 = Jose ( num, 2, 0 );
        printf("%d\n",res+1);
    }
    return 0;
}


你可能感兴趣的:(POJ 1781 In Danger 约瑟夫环(log(m)))