Yet Another Multiple Problem-----BFS

Problem Description
There are tons of problems about integer multiples. Despite the fact that the topic is not original, the content is highly challenging. That’s why we call it “Yet Another Multiple Problem”.
In this problem, you’re asked to solve the following question: Given a positive integer n and m decimal digits, what is the minimal positive multiple of n whose decimal notation does not contain any of the given digits?
 

Input
There are several test cases.
For each test case, there are two lines. The first line contains two integers n and m (1 ≤ n ≤ 10 4). The second line contains m decimal digits separated by spaces.
Input is terminated by EOF.
 

Output
For each test case, output one line “Case X: Y” where X is the test case number (starting from 1) while Y is the minimal multiple satisfying the above-mentioned conditions or “-1” (without quotation marks) in case there does not exist such a multiple.
 

Sample Input
  
  
2345 3 7 8 9 100 1 0
 

Sample Output
  
  
Case 1: 2345 Case 2: -1
 

Source

#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
#include<algorithm>
#include<cmath>
using namespace std ;
const int N=10005;

bool vis[N],del[N];//是否访问的记录数组,以及禁忌梳子记录数组;
int n,pre[N];//记录前置数字来输出 
char text[N];//为输出准备数组

bool BFS()
{
	queue<int>Q;
	Q.push(0);
	int cur;
	while(!Q.empty())
	{
		cur=Q.front();
		Q.pop();
		for(int i=0;i<10;i++)
		{
			if(del[i]==1||cur==0&&i==0){//如果是不允许使用的数字或者当前余数和数字都为0,继续
			     continue;
			}
			int yu=(cur*10+i)%n;//计算新的余数;
			if(vis[yu]) {//已经到达过 ,不保存
			   continue; 
			}
			text[yu]='0'+i;//记录到达新的余数的数字i;
			vis[yu]=true;
			pre[yu]=cur;//记录到达这个余数的前面那个余数
			Q.push(yu);
			if(yu==0){//若此时的余数为0,说明获得答案,退出;
			   return true; 
			} 
		}
	}
	return false;
 } 
 void print()
 {
 	string ans;
 	int p=0;
 	while(p!=0||ans.empty()){//如果p不为0或者ans为空
	   ans+=text[p];//添加数字
	   p=pre[p];//寻找前缀 
	 }
	 reverse(ans.begin(),ans.end());//反转
	 puts(ans.c_str()); 
 }
int main()
{
	int m,cas=0;
	while(scanf("%d%d",&n,&m)!=EOF){
		memset(vis,0,sizeof(vis));//初始化
		memset(del,0,sizeof(del));
		while(m--){
			int k;
			scanf("%d",&k);
			del[k]=1;//设置这个数字不能出现 
		}
		printf("Case %d: ",++cas);
		if(!BFS()){
			printf("-1\n");
		}
		else
		    print(); 
	}
	return 0;
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值