標籤:
Different DigitsTime Limit: 10000/4000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1138 Accepted Submission(s): 296
Problem DescriptionGiven a positive integer n, your task is to find a positive integer m, which is a multiple of n, and that m contains the least number of different digits when represented in decimal. For example, number 1334 contains three different digits 1, 3 and 4.
InputThe input consists of no more than 50 test cases. Each test case has only one line, which contains a positive integer n ( 1<=n < 65536). There are no blank lines between cases. A line with a single `0‘ terminates the input.
OutputFor each test case, you should output one line, which contains m. If there are several possible results, you should output the smallest one. Do not output blank lines between cases.
Sample Input
7 15 16 101 0
Sample Output
7555161111
題意:告訴一個數n,求一個他的倍數m,使得m由最少的不同數字組成。
思路:對於任意一個n,都可以找到一個他的倍數,並且這個倍數只有最多2種不同的數字組成。所以,可以分成1種和2種討論下。
#include <iostream>#include <stdio.h>#include <string>#include <cstring>#include <algorithm>#include <cmath>#include <queue>using namespace std;struct Node{ int mod; string ans;}f,t;int n;string ans,tmp;int num[2];int vis[70000];int bfs1(){ int flag=0; for(int i=1;i<=9;i++) { f.mod=i%n; f.ans=""; f.ans+=i+'0'; while(f.ans.size()<n && f.mod!=0) { f.ans+=i+'0'; f.mod=(f.mod*10+i)%n; } if(f.mod==0) { if(flag==0) {tmp=f.ans;flag=1;} else if(f.ans.size()<tmp.size()) tmp=f.ans; else if(f.ans.size()==tmp.size() && f.ans<tmp) tmp=f.ans; } } if(flag) {ans=tmp;return 1;} else return 0;}void bfs2(){ memset(vis,0,sizeof vis); queue<Node>q; for(int i=0;i<2;i++) { if(num[i]==0) continue; f.mod=num[i]%n; f.ans=""; f.ans+=num[i]+'0'; vis[f.mod]=1; q.push(f); } int flag=0; while(!q.empty()) { f=q.front(); q.pop(); if(flag) { if(f.mod==0) { if(tmp.size()>f.ans.size()) {tmp=f.ans;continue;} else if(tmp.size()==f.ans.size() && tmp>f.ans) {tmp=f.ans;continue;} } } else if(f.mod==0) { flag=1; tmp=f.ans; continue; } for(int i=0;i<2;i++) { t=f; t.ans+=num[i]+'0'; t.mod=(f.mod*10+num[i])%n; if(vis[t.mod]) continue; vis[t.mod]=1; q.push(t); } } if(ans=="") ans=tmp; else if(ans.size()>tmp.size()) ans=tmp; else if(ans.size()==tmp.size() && ans>tmp) ans=tmp;}int main(){ while(scanf("%d",&n),n) { ans=""; if(bfs1()); else { for(int i=0;i<9;i++) for(int j=i+1;j<=9;j++) { num[0]=i;num[1]=j; bfs2(); } } cout<<ans<<endl; } return 0;}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
hdu 1664 Different Digits