poj 1465Multiple 數位bfs,手寫佇列,同餘剪枝
Multiple
Time Limit: 1000MS | Memory Limit: 32768K | |
Total Submissions: 8373 | Accepted: 1851 |
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
22 3 7 0 1 2 1 1
Sample Output
110 0
Source
記錄餘數r,每一位的數dig,前驅pre,用陣列記錄一下餘數,如果餘數出現過,就不用擴充套件了,這裡要找最小的倍數,先把這些書排一下序,這題要輸出這個數,可以手寫佇列,便於儲存。另外,注意判斷一下n為0的情況,不然re,再就是注意輸出的格式
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define maxn 5050 int n,m; int dig[15]; int flag[maxn]; struct node { int dig; int r; int pre; }q[maxn]; int bfs() { memset(flag,0,sizeof(flag)); int front=0,tail=1; q[front].pre=-1; q[front].dig=0; q[front].r=0; while(front<tail) { node node=q[front]; int r=node.r; for(int i=0;i<m;i++) { int nr=(r*10+dig[i])%n; if(!flag[nr]&&(node.pre!=-1||dig[i]!=0)) { flag[nr]=1; node.r=nr; node.dig=dig[i]; node.pre=front; q[tail++]=node; if(nr==0) return tail-1; } } front++; } return -1; } void print(int ans) { if(ans>0) { print(q[ans].pre); printf("%d",q[ans].dig); } } int main() { while(~scanf("%d",&n)) {scanf("%d",&m); for(int i=0;i<m;i++) scanf("%d",&dig[i]); sort(dig,dig+m); if(n==0) {printf("0\n"); continue; } int ans=bfs(); if(ans==-1) printf("0\n"); else {print(ans); printf("\n"); } } return 0; }