Ignatius花了一个星期的时间终于找到了传说中的宝藏,宝藏被放在一个房间里,房间的门用密码锁起来了,在门旁边的墙上有一些关于密码的提示信息:
密码是一个C进制的数,并且只能由给定的M个数字构成,同时密码是一个给定十进制整数N(0<=N<=5000)的正整数倍(如果存在多个满足条件的数,那么最小的那个就是密码),如果这样的密码存在,那么当你输入它以后门将打开,如果不存在这样的密码......那就把门炸了吧.
注意:由于宝藏的历史久远,当时的系统最多只能保存500位密码.因此如果得到的密码长度大于500也不能用来开启房门,这种情况也被认为密码不存在.
Input
输入数据的第一行是一个整数T(1<=T<=300),表示测试数据的数量.每组测试数据的第一行是两个整数N(0<=N<=5000)和C(2<=C<=16),其中N表示的是题目描述中的给定十进制整数,C是密码的进制数.测试数据的第二行是一个整数M(1<=M<=16),它表示构成密码的数字的数量,然后是M个数字用来表示构成密码的数字.两个测试数据之间会有一个空行隔开.
注意:在给出的M个数字中,如果存在超过10的数,我们约定用A来表示10,B来表示11,C来表示12,D来表示13,E来表示14,F来表示15.我保证输入数据都是合法的.
Output
对于每组测试数据,如果存在要求的密码,则输出该密码,如果密码不存在,则输出"give me the bomb please".
注意:构成密码的数字不一定全部都要用上;密码有可能非常长,不要试图用一个整型变量来保存密码;我保证密码最高位不为0(除非密码本身就是0).
Sample Input
3 22 10 3 7 0 1 2 10 1 1 25 16 3 A B C
Sample Output
110 give me the bomb please CCB Huge input, scanf is recommended.
Hint
Hint
思路:只是一道广搜题,从小的树开始找,细心一点就可以。
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
#define inf 0x3f3f3f3f
struct lou
{
char x;
int yu;
int z;
int zz;
} s[100000];
char st[20];
int book[5010];
int main()
{
int t,n,C,M,i;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&C);
scanf("%d",&M);
for(i=0; i<M; i++)
{
getchar();
scanf("%c",&st[i]);
}
sort(st,st+M);
memset(book,0,sizeof(book));
if(n==0)
{
if(st[0]=='0')
printf("0\n");
else
printf("give me the bomb please\n");
}
else
{
int head=0,tail=0,a;
if(st[0]=='0')
{
for(i=1; i<M; i++)
{
if(st[i]>='0'&&st[i]<='9')
a=st[i]-'0';
else
a=st[i]-'A'+10;
a=a%n;
if(book[a]==0)
{
book[a]=1;
s[tail].x=st[i];
s[tail].yu=a;
s[tail].z=1;
s[tail].zz=-1;
tail++;
}
}
}
else
{
for(i=0; i<M; i++)
{
if(st[i]>='0'&&st[i]<='9')
a=st[i]-'0';
else
a=st[i]-'A'+10;
a=a%n;
if(book[a]==0)
{
book[a]=1;
s[tail].x=st[i];
s[tail].yu=a;
s[tail].z=1;
s[tail].zz=-1;
tail++;
}
}
}
int flag=0;
char dis[510];
int k=0,tt;
while(head<tail)
{
if(s[head].yu==0)
{
flag=1;
dis[k++]=s[head].x;
tt=head;
while(s[tt].zz!=-1)
{
tt=s[tt].zz;
dis[k++]=s[tt].x;
}
while(k--)
{
printf("%c",dis[k]);
}
printf("\n");
break;
}
if(s[head].z>=500)
{
head++;
continue;
}
for(i=0; i<M; i++)
{
if(st[i]>='0'&&st[i]<='9')
a=st[i]-'0';
else
a=st[i]-'A'+10;
a=(s[head].yu*C+a)%n;
if(book[a]==0)
{
book[a]=1;
s[tail].x=st[i];
s[tail].yu=a;
s[tail].z=s[head].z+1;
s[tail].zz=head;
tail++;
}
}
head++;
}
if(flag==0)
printf("give me the bomb please\n");
}
}
return 0;
}