您的位置:首页 > 其它

HDU 4474(神奇的BFS+强剪枝)

2015-08-26 20:22 246 查看

HDU - 4474
Yet Another Multiple Problem

Time Limit: 20000MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u
            

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.
 

Sample Input

2345 3
7 8 9
100 1
0

 

Sample Output

Case 1: 2345
Case 2: -1

 

Hint

Source
2012 Asia Chengdu Regional Contest

题意:

给出一个数字n,和m个一位数字,求n的最小倍数,使得其中不会出现这m个数字。
思路:

开始想的是暴力枚举一下= = 结果发现根本找不到一个上界,果断弃疗。
其实一个BFS,再加一个优化就可以解决。
同余剪枝:对于每次搜索到的数x, 判断一下 x mod n 是否已经存在。如果存在的话,说明有比当前结果更优的解,直接跳过。直到x mod n == 0,回溯输出ans。

AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n, m, a[15],mod[10000+5],ans[10000+5],pre[100000+5];
bool flag;
void print(int u)
{
if(u == -1) return;
print(pre[u]);
printf("%d",ans[u]);
return;
}
void bfs()
{
queue<int> q;
for(int i = 1;i < 10;i ++)
{
if(!a[i])
{
if(mod[i%n] == 1) continue;
q.push(i%n);
ans[i%n] = i;
mod[i%n] = 1;
}
}
while(!q.empty())
{
int u = q.front();
//cout << u<<endl;
q.pop();
if(u == 0)
{
flag = 1;
print(u);
return;
}
for(int i = 0;i < 10;i ++)
{
if(!a[i])
{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int x = (u*10 + i) % n;    //同余剪枝
if(mod[x] == -1)
{
mod[x] = 1;
ans[x] = i;
pre[x] = u;
q.push(x);    //这里只需要将x放进队列即可
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
}
}
}
printf("-1");
}
int main()
{
int cases = 1;
while(scanf("%d%d", &n, &m) != EOF)
{
flag = 0;
memset(a, 0, sizeof(a));
memset(mod,-1,sizeof(mod));
memset(pre,-1,sizeof(pre));
while(m --)
{
int x;
scanf("%d", &x);
a[x] = 1;
}
printf("Case %d: ",cases ++);
bfs();
printf("\n");
}
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ACM