其实很简单的思想,外加贴一个模版
【题目描述】给一个数N 然后给M个一位数 问你是否有N的倍数 完全由这些一位数组成
先说算法 用BFS不停的扩展 就是X10这样的扩展 然后如果对N取余的余数没有出现过就把这个扩展得数的余数添加到队列里 如果余数是0的话就可以输出了
当然 扩展的时候要考虑到0,这些都不是最关键的 最关键的是这个数可能非常大 long long 不够 而高精的话比较麻烦。用链表。
还有一点 这个队列最多只有5000就够了。
另外 不需要证明所有的余数都取到了 没有必要
/******************************************************************************************************
** Copyright (C) 2011.07.01-2013.07.01 ** Author: famousDT <[email protected]> ** Edit date: 2012-03-11 ******************************************************************************************************/ #include <stdio.h> #include <stdlib.h>//abs,atof(string to float),atoi,atol,atoll #include <math.h>//atan,acos,asin,atan2(a,b)(a/b atan),ceil,floor,cos,exp(x)(e^x),fabs,log(for E),log10 #include <vector> #include <queue> #include <deque>//two direction queue #include <map> #include <time.h> #include <set> #include <list> #include <stack> #include <string> #include <iostream> #include <fstream> #include <assert.h> #include <bitset> #include <iterator>//C++Primer #include <string.h>//memcpy(to,from,count #include <ctype.h>//character process:isalpha,isdigit,islower,tolower,isblank,iscntrl,isprll #include <numeric> #include <utility>//pair #include <functional> #include <algorithm> using namespace std; typedef long long int ll; #define MY_E exp(1.0) #define MY_PI acos(-1.0) #define MY_MAX(a, b) ((a) > (b) ? (a) : (b)) #define MY_MIN(a, b) ((a) < (b) ? (a) : (b)) #define MY_MALLOC(n, type) ((type *)malloc((n) * sizeof(type))) #define MY_ABS(a) (((a) >= 0) ? (a) : (-(a))) #define MY_INT_MAX 0x7fffffff #define CLEAR(a) memset(a, 0, sizeof(a)) /*==========================================================*\ | \*==========================================================*/ #define N 5000 + 5 struct node { int res; //余数 int digit; //位数 node *pre; } q[N]; bool hash[N]; void output(node x) { if (x.pre) { output(*x.pre); printf("%d", x.digit); } } void bfs(int n, int m, int d[]) { int i, j; CLEAR(hash); int front = 0, rear = 1; q[0].pre = NULL; q[0].digit = q[0].res = 0; node * first = &q[0]; while (front < rear) { node now, curr = q[front]; now.pre = &q[front]; for (i = 0; i < m; ++i) { int res = (curr.res * 10 + d[i]) % n; if (hash[res] == 0 && (now.pre != first || d[i] > 0)) { hash[res] = true; now.res = res; now.digit = d[i]; q[rear++] = now; if (now.res == 0) { output(now); printf("\n"); return; } } } ++front; } printf("0\n"); } int main() { int m, n; int d[15]; int i; while (scanf("%d%d", &n, &m) == 2) { for (i = 0; i < m; ++i) scanf("%d", &d[i]); if (!n) { printf("0\n"); continue; } sort(d, d + m); bfs(n, m, d); } return 0; }