算法:用5,7,12加减运算,求最少步数得到任意数n
rt
[解决办法]
O(1)时间复杂度。
/*** 用5,7,12加减运算,最少步骤到大n* gogdizzy@gmail.com*/#include <stdio.h>#define abs(x) \ ( (x^(x>>31))-(x>>31) )int min_step( int N ){ int diff; int n5, n7, n12; int r5, r7, r12; unsigned tmp, total = unsigned (-1); // assign a very big num for( n5 = -6; n5 < 7; ++n5 ) { diff = N - 5 * n5; n7 = diff / 7; n12 = diff / 12; if( 12 * n12 + 5 * n5 == N ) { tmp = abs( n5 ) + abs( n12 ); if( total > tmp ) r5 = n5, r7 = 0, r12 = n12, total = tmp; } else if( 7 * n7 + 5 * n5 == N ) { if( n7 > -12 && n7 < 12 ) { tmp = abs( n5 ) + abs( n7 ); if( total > tmp ) r5 = n5, r7 = n7, r12 = 0, total = tmp; } } } for( n7 = -11; n7 < 12; ++n7 ) { n12 = ( N - 7 * n7 ) / 12; if( 7 * n7 + 12 * n12 == N ) { tmp = abs( n7 ) + abs( n12 ); if( total > tmp ) r5 = 0, r7 = n7, r12 = n12, total = tmp; } } printf( "%d = (%d) * 5 + (%d) * 7 + (%d) * 12\ntotal:%d\n", N, r5, r7, r12, total ); return total;}int main(){ int n; scanf( "%d", &n ); min_step( n ); return 0;}
[解决办法]