HDU1226 BFS
题意:给定n,m,c 和 k个数
求最小的一个数(这个数是c进制,且是n的倍数)
一共5000个状态,bfs
不会写DFS啊。。。。
不过看了别人的BFS后还是有种恍然大悟的感觉。。。。
View Code
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string> 4 #include<algorithm> 5 #include<math.h> 6 #include<iostream> 7 #include<queue> 8 using namespace std; 9 const int maxn = 24; 10 const int maxm = 5105; 11 const int inf = 99999999; 12 int n,m,c; 13 int a[ maxn ]; 14 int vis[ maxm ]; 15 int flag; 16 struct node{ 17 string ans; 18 int mod; 19 }; 20 string res; 21 queue<node>q; 22 void init2(){ 23 while( !q.empty() ) 24 q.pop(); 25 } 26 void init1(){ 27 memset( a,0,sizeof( a )); 28 memset( vis,0,sizeof( vis )); 29 flag=-1; 30 res.clear(); 31 } 32 void bfs(){ 33 init2(); 34 node now,next; 35 for( int i=1;i<16;i++ ){ 36 if( a[i] ){ 37 vis[ i%n ]=1; 38 if( i>=0&&i<=9 ){ 39 now.ans=""; 40 now.ans=(i+'0'); 41 now.mod=i%n; 42 q.push( now ); 43 } 44 else{ 45 now.ans=""; 46 now.ans=(i+'A'-10); 47 now.mod=i%n; 48 q.push( now ); 49 } 50 } 51 }//the init 52 while( !q.empty() ){ 53 now=q.front(),q.pop(); 54 if( flag==1&&now.ans.size()>res.size() ) 55 continue; 56 if( now.mod==0 ){ 57 if( flag==-1 ){ 58 flag=1; 59 res=now.ans; 60 } 61 else{ 62 if( now.ans.size()<res.size() ){ 63 res=now.ans; 64 } 65 else if( now.ans.size()==res.size()&&res>now.ans ){ 66 res=now.ans; 67 } 68 } 69 } 70 for( int i=0;i<16;i++ ){ 71 if( a[i] ){ 72 if( i<10 ){ 73 next=now; 74 next.ans+=( i+'0' ); 75 next.mod=(now.mod*c+i)%n; 76 if( ( next.ans.size()<=500&&vis[ next.mod ]==0 )||( next.mod==0 ) ){ 77 vis[ next.mod ]=1; 78 q.push( next ); 79 } 80 } 81 else{ 82 next=now; 83 next.ans+=(i+'A'-10); 84 next.mod=(now.mod*c+i)%n; 85 if( ( next.ans.size()<=500&&vis[ next.mod ]==0 )||( next.mod==0 ) ){ 86 vis[ next.mod ]=1; 87 q.push( next ); 88 } 89 } 90 } 91 } 92 } 93 } 94 95 int main(){ 96 int ca; 97 scanf("%d",&ca); 98 while( ca-- ){ 99 scanf("%d%d%d",&n,&c,&m); 100 init1(); 101 char ch[ 4 ]; 102 for( int i=0;i<m;i++ ){ 103 scanf("%s",ch); 104 if( ch[0]>='0'&&ch[0]<='9' ) 105 a[ ch[0]-'0' ]=1; 106 else 107 a[ ch[0]-'A'+10 ]=1; 108 } 109 if(n==0){ 110 // cout<<0<<endl; 111 if(a[0]==1) 112 cout<<0<<endl; 113 else 114 cout<<"give me the bomb please"<<endl; 115 continue; 116 } 117 bfs(); 118 if( flag==-1 ) 119 printf("give me the bomb please\n"); 120 else 121 cout<<res<<endl; 122 } 123 return 0; 124 }
keep moving...