POJ-1465 Multiple
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.
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:
An example of input and output:
Sample Input
22 3 7 0 1 2 1 1
Sample Output
110 0
题目大意:
给你一个数n还有m个个位数,让你找到n的最小的倍数,无法找到就输出0.
解题思路:
BFS+余数判重
具体思路在我的另外一篇博客里面有
这题坑点很多。比如卡STL时间,当n为0的时候要输出0等等= =
代码:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 5000 + 10; typedef struct node{ int pre; int mod; int digit; }Queue; int n, m; int a[maxn]; int vis[maxn]; Queue q[maxn]; void print(Queue p){ if(p.pre > -1) print(q[p.pre]); printf("%d", p.digit); } void bfs(){ int front = 0, rear = 0; for(int i = 0; i < maxn; ++i){ vis[i] = 0; q[i].pre = -1; q[i].mod = q[i].digit = 0; } for(int i = 0; i < m; ++i){ if(!a[i]) continue; if(a[i] % n == 0) { printf("%d\n", a[i]); return; } if(!vis[ a[i] % n ]){ vis[ a[i] % n ] = 1; q[rear].mod = a[i] % n; q[rear].digit = a[i]; ++rear; } } while(front < rear){ Queue tmp, p = q[front++]; if(p.mod == 0){ print(p); puts(""); return; } for(int i = 0; i < m; ++i){ tmp.mod = (p.mod * 10 + a[i]) % n; tmp.digit = a[i]; tmp.pre = front - 1; if(!vis[tmp.mod]) { vis[tmp.mod] = 1; q[rear++] = tmp; } } } puts("0"); } int main() { // freopen("test.in", "r+", stdin); // freopen("test.out", "w+", stdout); while(~scanf("%d", &n)){ scanf("%d", &m); for(int i = 0; i < m; ++i){ scanf("%d", &a[i]); } sort(a, a + m); if(n == 0) puts("0"); else bfs(); } return 0; }