Yet Another Multiple Problem
Time Limit: 40000/20000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 6291 Accepted Submission(s): 1460
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?
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.
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 <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
#include <string>
#define N 10005
using namespace std;
bool del[10],vis[N]; //vis标记余数,再次出现只记录第一次,第一次出现的最小
int n,pre[N];//记录前缀数组
char text[N];//记录输出
void Print() //因为是记录前缀,所以逆置后输出;
{
string ans;
int p=0;
while(p!=0 || ans.empty())
{
ans+=text[p];
p=pre[p];
}
reverse(ans.begin(),ans.end());
cout<<ans<<endl;
}
bool bfs()
{
queue <int> q;
int cur;
q.push(0);
while(!q.empty())
{
cur=q.front();
q.pop();
for(int i=0;i<10;i++)
{
if(del[i] || (cur==0 && i==0))
continue;
int yu=(cur*10+i)%n;
if(vis[yu])
continue;
text[yu]='0'+i;
vis[yu]=1;
pre[yu]=cur;
q.push(yu);
if(yu==0)
return 1;
}
}
return 0;
}
int main()
{
int m,cnt=0;
while(~scanf("%d%d",&n,&m))
{
memset(vis,0,sizeof(vis));
memset(del,0,sizeof(del));
while(m--)
{
int k;
scanf("%d",&k);
del[k]=1;
}
printf("Case %d: ",++cnt);
if(!bfs())
printf("-1\n");
else
Print();
}
return 0;
}