超级密码

Time Limit: 20000/10000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3866    Accepted Submission(s): 1241

Problem Description
Ignatius花了一个星期的时间终于找到了传说中的宝藏,宝藏被放在一个房间里,房间的门用密码锁起来了,在门旁边的墙上有一些关于密码的提示信息:

码是一个C进制的数,并且只能由给定的M个数字构成,同时密码是一个给定十进制整数N(0<=N<=5000)的正整数倍(如果存在多个满足
条件的数,那么最小的那个就是密码),如果这样的密码存在,那么当你输入它以后门将打开,如果不存在这样的密码......那就把门炸了吧.

注意:由于宝藏的历史久远,当时的系统最多只能保存500位密码.因此如果得到的密码长度大于500也不能用来开启房门,这种情况也被认为密码不存在.

 
Input

入数据的第一行是一个整数T(1<=T<=300),表示测试数据的数量.每组测试数据的第一行是两个整数N(0<=N&
lt;=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

Hint

Hint

Huge input, scanf is recommended.

 
Author
Ignatius.L
 
Source
 
题解:强大的同余剪枝,如果某个数 a%n == b%n (a<b) 如果目标状态为 (a + c)%n == 0,而(a+c)%n = a%n + c%n = b%n + c%n ,所以搜索 a b是等价的,但是我们要的是最小的解,所以我们可以不再去找b,所以我们标记余数,这样的话可以剪掉非常多的状态,这样的话就不会超时了.
所以具体解法为排序后进行同余搜索,0要特判。
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;
int n,c,m;
bool mod[];
char num[];
struct Node{
int mod;
string ans;
int len;
};
void bfs(){
memset(mod,,sizeof(mod));
queue<Node> q;
Node s;
for(int i=;i<=m;i++){
if(num[i]!='') {
s.ans= num[i];
if(isdigit(num[i])) s.mod = (num[i]-'')%n;
else s.mod = (num[i]-'A'+)%n;
s.len = ;
q.push(s);
}
}
while(!q.empty()){
Node now = q.front();
q.pop();
//cout<<now.ans<<endl;
if(now.len>) {
printf("give me the bomb please\n");
return;
}
if(now.mod==){
cout<<now.ans<<endl;
return ;
}
Node next;
for(int i=;i<=m;i++){
next.ans = now.ans+num[i];
if(isdigit(num[i])) next.mod = (now.mod*c+(num[i]-''))%n;
else next.mod = (now.mod*c+(num[i]-'A'+))%n;
//cout<<next.ans<<endl;
next.len=now.len+;
if(mod[next.mod]) continue;
mod[next.mod]=true;
q.push(next);
}
}
printf("give me the bomb please\n");
return;
}
int main(){
int tcase;
scanf("%d",&tcase);
while(tcase--){
scanf("%d%d",&n,&c);
scanf("%d",&m);
bool flag = false;
getchar();
for(int i=;i<m;i++){
scanf("%c ",&num[i]);
if(n==&&num[i]=='') flag = true;
}
scanf("%c",&num[m]);
if(n==&&num[m]=='') flag = true;
sort(num+,num++m);
if(n==){
if(flag){
printf("0\n");
continue;
}else{
printf("give me the bomb please\n");
continue;
}
}
bfs();
}
return ;
}
05-20 12:51