题目链接:http://poj.org/problem?id=1426
简单的搜索题,一开始想着用bfs,结果TLE了,看有用dfs写A掉了,就用dfs写,过然AC了。
bfs超时的代码:
1 ///2014.4.7 2 ///poj1426 3 4 #include <iostream> 5 #include <cstdio> 6 #include <algorithm> 7 #include <cstring> 8 using namespace std; 9 10 const int MaxLength = 1000000; 11 unsigned long long queue[MaxLength]; 12 int n; 13 14 unsigned long long bfs( ){ 15 memset(queue,0,sizeof(queue) ); 16 int head,tail; 17 head = 0; 18 tail = 1; 19 queue[0] = 1; 20 21 while( true ){ 22 queue[tail] = queue[head] * 10; 23 if( queue[tail] % n == 0 ) 24 break; 25 tail++; 26 27 queue[tail] = queue[head] * 10 + 1; 28 if( queue[tail] % n == 0 ) 29 break; 30 tail++; 31 32 head++; 33 } 34 return queue[tail]; 35 } 36 37 int main() 38 { 39 // freopen("in","r",stdin); 40 // freopen("out","w",stdout); 41 42 while( cin>>n && n ){ 43 cout<<bfs( )<<endl; 44 } 45 return 0; 46 }
dfs代码,141MS通过:
1 ///2014.4.7 2 ///poj1426 3 4 #include <iostream> 5 #include <cstdio> 6 using namespace std; 7 8 bool found; 9 int n; 10 11 void dfs(unsigned long long a,int deep){ 12 if(found) 13 return; 14 if( a%n == 0 ){ 15 found = true; 16 cout<<a<<endl; 17 return; 18 } 19 if( deep>=19 ) 20 return; 21 dfs(a*10,deep+1); 22 dfs(a*10+1,deep+1); 23 } 24 25 int main() 26 { 27 // freopen("in","r",stdin); 28 // freopen("out","w",stdout); 29 30 while( cin>>n && n ){ 31 found = false; 32 dfs(1,0); 33 } 34 return 0; 35 }
poj1426 Find The Multiple 简单搜索,布布扣,bubuko.com
poj1426 Find The Multiple 简单搜索
原文:http://www.cnblogs.com/basement-boy/p/3649986.html