HDU 4474(神奇的BFS+强剪枝)
2015-08-26 20:22
246 查看
HDU - 4474 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. 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网址
- 1272 小希的迷宫
- 1272 小希的迷宫
- hdu 1250 大数相加并用数组储存
- 矩阵的乘法操作
- 蚂蚁爬行问题
- 蚂蚁爬行问题
- 求两个数的最大公约数【ACM基础题】
- 打印出二进制中所有1的位置
- 杭电题目---一只小蜜蜂
- HDOJ 1002 A + B Problem II (Big Numbers Addition)
- POJ ACM 1002
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- HDU 1568
- HDU1290