首页 > 代码库 > hdu 1226 超级密码

hdu 1226 超级密码

暴力搜索 用字符匹配,直至符合或者超出范围

  1 #include<cstdio>  2 #include<memory.h>  3 #include<queue>  4 #include<string>  5 using namespace std;  //不加的话queue的声明无法通过  6 int n,c;  7 int visit[5001];//标记余数  n:0-5000  8 int num[16];  9 struct ss 10 { 11     int a[502]; 12     int len; 13 }; 14  15 int mod(ss t) 16 { 17     int tt = 0; 18     for(int i = 0; i < t.len; i++) 19         tt = (tt * c + t.a[i]) % n; 20     return tt; 21 } 22  23 void print(ss t) 24 { 25     for(int i = 0; i < t.len; i++) 26     { 27         if(t.a[i] <= 9) 28             printf("%d",t.a[i]); 29         else 30             printf("%c",t.a[i] - 10 + A); 31     } 32     printf("\n"); 33 } 34 int bfs() 35 { 36     memset(visit,0,sizeof(visit)); 37     ss s; 38     int modd; 39     queue<ss> q; 40     for(int i = 1; i < 16; i++) 41     { 42         if(num[i]) 43         { 44             s.a[0] = i; 45             s.len = 1; 46             modd = mod(s); 47             if(!modd)  //模为0 48             { 49                 print(s); 50                 return 1; 51             } 52             else 53             { 54                 //q.push(s); 55                 if(!visit[modd]) 56                 { 57                     visit[modd] = 1; 58                     q.push(s); 59                 } 60             } 61         } 62     } 63     while(!q.empty()) 64     { 65         s = q.front(); 66         q.pop(); 67         for(int i = 0; i < 16; i++) 68         { 69             if(num[i]) 70             { 71                 s.a[s.len] = i; 72                 s.len++; 73                 modd = mod(s); 74                 if(!modd) 75                 { 76                     print(s); 77                     return 1; 78                 } 79                 else 80                 { 81                     if(!visit[modd] && s.len < 499) 82                     { 83                         visit[modd] = 1; 84                         q.push(s); 85                     } 86                 } 87  88                 s.len--; //恢复 89             } 90         } 91  92     } 93     return 0; 94 } 95  96 int main() 97 { 98     freopen("input.txt","r",stdin); 99     int T,m;100     char ch[2];  //注意字符存取 后面要有一个空间存取‘\0‘101     scanf("%d",&T);102     while(T--)103     {104         scanf("%d%d",&n,&c);105         scanf("%d",&m);106         memset(num,0,sizeof(num));107         for(int i = 0; i < m; i++)108         {109             scanf("%s",&ch);110             if(ch[0] >= 0 && ch[0] <=9)111                 num[ch[0]-0] = 1;112             else113                 num[ch[0]-A+10] = 1;114         }115 116         if(n == 0)117         {118             if(num[0])119                 printf("%d\n",0);120             else121                 printf("give me the bomb please\n");122         }123         else124         {125             bool b = bfs();126             if(!b)127                 printf("give me the bomb please\n");128         }129 130     }131     return 0;132 }