POJ 1781
约瑟夫环的二进制解法。
当n=2*k,
序列1:1,2,3...2*k
序列2:1,3,5..2*k-1(k个)
序列3:1,2,3...k
所以有f(2*k) = 2*f(k) - 1。
当n=2*k-1,
序列1:1,2,3...2*k-1
序列2:3,5,7...2*k-1(k个)
序列3:1,2,3...k
所以有f(2*k+1) = 2*f(k) + 1。
View Code
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 typedef long long int ll; 5 6 ll get_num(ll x) 7 { 8 if (x == 1)return 1; 9 if (x&1)return (2*get_num(x/2)+1); 10 else return (2*get_num(x/2)-1); 11 } 12 13 int main() 14 { 15 ll n,m; 16 while (scanf("%I64de%I64d",&n,&m) && !(n == 0 && m == 0)) { 17 for (int i(0); i<m; ++i) { 18 n *= 10; 19 } 20 printf("%I64d\n",get_num(n)); 21 } 22 return 0; 23 }