B . Yet Another Multiple Problem

B . Yet Another Multiple 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≤104 ).

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.

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
struct node {
	char c;
	int m,f;//f记录的是答案的路径;
} temp,q[100001];
int use[11];
int vis[100001];
void out(int a) {
	if(a==-1)
		return ;
	out(q[a].f);
	printf("%c",q[a].c);
}
int main() {
	int n,m;
	ll ans=-1,t=0;
	while(~scanf("%d %d",&n,&m)) {
		memset(use,0,sizeof(use));
		memset(vis,0,sizeof(vis));
		//printf("Case %d: ",++t);
		ans=-1;
		for(int i=1; i<=m; i++) {
			int e;
			cin>>e;
			use[e]=1;
		}
		printf("Case %d: ",++t);
		int l,r;
		l=r=0;
		for(int i=1; i<=9; i++) {//从1开始遍历可以用的所有数保证搜到的答案是递增的。
			if(use[i]==0) {
				temp.c=i+'0';
				temp.m=i%n;
				vis[temp.m]=1;
				temp.f=-1;//递归输出打底条件
				q[r++]=temp;
				if(temp.m==0) {
					ans=r-1;
					break;
				}
			}
		}//先打个底
		while(l<r&&ans==-1) {
			for(int i=0; i<=9; i++) {
				if(use[i]==0) {
					temp.c=i+'0';
					temp.m=(q[l].m*10+i)%n;
					if(vis[temp.m]==0) {
						vis[temp.m]=1;
						temp.f=l;
						q[r++]=temp;
						if(!temp.m) {
							ans=r-1;
							break;
						}
					}
				}
			}
			l++;
		}
		if(ans==-1)
			cout<<-1<<endl;
		else {
			out(ans);
			cout<<endl;
		}
	}
	return 0;
}

为什么要记录每个数对n去摸的值呢:
假设a%n=b%n,a<b;
有两种情况:
1.a%n=0,因为我们再搜每个数的时候保证了整个数列的递增,所以a肯定出现在b前面。
2.a%n!=0.a和b我们都继续往后填数,就会出现这(a*10+i)%n=(b*10+i)%n。也就是说对答案的贡献是一样的,这样的话后面的就不必取了,因为我们取得终归是最小值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值