Multiple
| Time Limit: 1000MS |
|
Memory Limit: 32768K |
| Total Submissions: 5625 |
|
Accepted: 1217 |
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 Source Southeastern Europe 2000 |
這題注意幾點:
1.從小往大的搜 得到最優解
2.取餘判重
3.特殊情況的處理 如0 或者開始就給出了n的倍數等
4.最後答案的位元可能很大 不能用int後long long 處理
我是這樣處理的 每一個節點只存有效值 以及加進來的dight 這樣就不用處理大數了
比如 n=7 現在擴充出來的為9 則有效值為2
因為如果A,B對於X的餘數相同
那麼
(10*A+d[i])%x
(10*B+d[i])%x
的意義是一樣的
感想:這題開始還是不敢下手的 後來下手了感覺也不是那麼難 敲出來了 不過WA了 因為我天真的用int處理了 ╮(╯▽╰)╭
代碼;
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#define maxn 5005using namespace std;int n,m,ans;int a[15];bool vis[maxn];struct Node{ int d; // 當前節點所加的dight int val; // 有效值 int pre; // 上一個節點編號}cur,now,q[maxn];bool bfs(){ int i,j,nx,tx; int head=0,tail=-1; memset(vis,0,sizeof(vis)); cur.pre=-1; for(i=1;i<=m;i++) { if(a[i]!=0&&!vis[a[i]%n]) { vis[a[i]%n]=1; cur.d=a[i]; cur.val=a[i]%n; q[++tail]=cur; } } while(head<=tail) { nx=q[head].val; if(nx%n==0) { ans=head; return true; } for(i=1;i<=m;i++) { tx=nx*10+a[i]; if(!vis[tx%n]) { vis[tx%n]=1; cur.d=a[i]; cur.pre=head; cur.val=tx%n; q[++tail]=cur; } } head++; } return false ;}void output(int k) // 遞迴輸出答案{ if(k==-1) return ; else { output(q[k].pre); printf("%d",q[k].d); }}int main(){ int i,j,flag; while(~scanf("%d",&n)) { flag=0; scanf("%d",&m); for(i=1;i<=m;i++) { scanf("%d",&a[i]); } if(n==0) { printf("0\n"); continue ; } sort(a+1,a+m+1); for(i=1;i<=m;i++) { if(a[i]%n==0&&a[i]!=0) { ans=a[i]; flag=1; break ; } } if(flag) { printf("%d\n",ans); continue ; } if(bfs()) output(ans); else printf("0"); printf("\n"); } return 0;}