2013年11月24日 星期日

UVa 440 - Eeny Meeny Moo

Problem link

Keyword: Joseph problem

Algorithm:

This problem is equivalent to Problem Power Crisis, and it can be solved using Joseph's algorithm.
Because the first city is cut off first, we have to modify the parameters of this algorithm.
First, the size of the city must be subtracted by 1 because the first one is gone at first.
Second, because the first one is already cut off, we also have to subtract 1 from the required place.
Then implement Joseph's algorithm to solve it.

Code:
#include<cstdio>
inline int joseph( int total, int per, int serial ) { return serial == 1? per % total : ( joseph( total-1, per, serial-1 ) + per ) % total; }

int main()
{
    int city, ans;

    while( scanf( "%d", &city ) && city )
    {
        for( ans = 1; joseph( city-1, ans, city-1 ); ++ans );
        printf( "%d\n", ans );
    }

    return 0;
}

沒有留言:

張貼留言