POJ-1465 Multiple

来源:互联网 发布:js转换dom 编辑:程序博客网 时间:2024/06/12 22:24
Multiple
Time Limit: 1000MS Memory Limit: 32768K 

Description

a program that, given a natural number N between 0 and 4999 (inclusively), and M distinct decimal digits X1,X2..XM (at least one), finds the smallest strictly positive multiple of N that has no other digits besides X1,X2..XM (if such a multiple exists).

Input

The input has several data sets separated by an empty line, each data set having the following format:

On the first line - the number N
On the second line - the number M
On the following M lines - the digits X1,X2..XM.

Output

For each data set, the program should write to standard output on a single line the multiple, if such a multiple exists, and 0 otherwise.

An example of input and output:

Sample Input

223701211

Sample Output

1100

————————————————————集训3.2的分割线————————————————————

前言:一道BFS做了一天……诶。

思路:首先是数论的知识,

同余定理 a % m == b % m -> (a-b) % m == 0        a1 == m*n + b1 -> a1 % m == b1 % m                        -> (a1*k+a2) % m == (b1*k+b2) % m

如果a1 % n == b1,那么a1和b1同余,因此对a进行的扩增操作用在b上得到的余数是一样的。也就是说a1*10+a2和b1*10+b2同余。所以虽然是大整数,但是不需要以数字进行保存。保存余数就行啦。每增加一个数字,求出(上一层余数×10+该数字)Mod n保存下来。用类似链表的方法,拆开保存这个大整数。一旦mod n == 0,即可回过头来进行递归输出。

剪枝:同余的数不应该出现一个以上,因为这两个数效果一样。所以不进队列。

队列:首位数字不能为0的处理——首位数字可以像别的数字一样在bfs里面进队,(避免单独写出来的繁琐以及可能的出错)只需要设置一个虚拟的队首即可。

代码如下:

/*ID: j.sure.1PROG:LANG: C++*//****************************************/#include <cstdio>#include <cstdlib>#include <cstring>#include <algorithm>#include <cmath>#include <stack>#include <queue>#include <vector>#include <map>#include <string>#include <iostream>using namespace std;/****************************************/int n, m;const int N = 5005;bool fuck[N];int num[10];struct Node{int val, fath, mod;}q[N];void PR(Node now){if(now.fath != -1) {PR(q[now.fath]);printf("%d", now.val);}}void bfs(){memset(fuck, 0, sizeof(fuck));q[0].val = 0;q[0].fath = -1;q[0].mod = 0;int fron = 0, rear = 1;Node t;while(fron < rear) {t = q[fron];for(int i = 0; i < m; i++) {if(t.fath == -1 && num[i] == 0)continue;Node nt;nt.val = num[i];nt.fath = fron;nt.mod = (t.mod*10 + nt.val) % n;if(nt.mod == 0) {PR(nt);puts("");return ;}if(!fuck[nt.mod]) {fuck[nt.mod] = 1;q[rear++] = nt;}}fron++;}puts("0");}int main(){while(~scanf("%d", &n)) {scanf("%d", &m);for(int i = 0; i < m; i++)scanf("%d", &num[i]);if(n == 0||m == 0) {puts("0");continue;}sort(num, num+m);bfs();}return 0;}


0 0
原创粉丝点击