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。也就是说对答案的贡献是一样的,这样的话后面的就不必取了,因为我们取得终归是最小值。