|
贴个效率较高的递归: /* * 回溯+最大-最小剪枝 */ #include <cstdlib> #include <iostream> #include <windows.h> using namespace std; const double pi=3.1415926; double best_pi=3.14; pair <int,int> best; int index[10]; int pos; double _abs( double n ){ return n>0? n : -n; }; int power[10][5]={ 0, 0, 0, 0, 0, 1,10,100,1000,10000, 2,20,200,2000,20000, 3,30,300,3000,30000, 4,40,400,4000,40000, 5,50,500,5000,50000, 6,60,600,6000,60000, 7,70,700,7000,70000, 8,80,800,8000,80000, 9,90,900,9000,90000 }; void f( int N, int D, int pos ){ if( pos==-1 ){ if( _abs(double(N)/D-pi) <_abs(best_pi-pi) ){ best=pair <int,int>(N,D); best_pi=double(N)/D; } return ; } int i, j, temp1, temp2; for( i=0; i <10; ++i ) if( index[i]==0 ){ index[i]=1; for( j=0; j <10; ++j ) if( index[j]==0 ){ index[j]=1; temp1=N+power[i][pos]; temp2=D+power[j][pos]; if( temp1+power[1][pos]>best_pi*temp2 && temp1 <best_pi*(temp2+power[1][pos]) ) f( temp1, temp2, pos-1 ); index[j]=0; } index[i]=0; } }; int main(int argc, char *argv[]){ int time=GetTickCount(); f( 0, 0, 4 ); cout < <best.first < <"/" < <best.second < <"==" < <best_pi < <endl; cout < <"Use time : " < <GetTickCount()-time < <" ms\n"; system("PAUSE"); return EXIT_SUCCESS; }
|