POJ - 1426 Find The Multiple (BFS、打表)
https://vjudge.net/problem/POJ-1426
题目
Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.
Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.
Output
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.
Sample Input
2
6
19
0
Sample Output
10
100100100100100100
111111111111111111
分析
直接打表

AC代码
BFS
#include<cstdio>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef long long LL;
int main()
{
LL n;
while(~scanf("%lld",&n) && n!=0)
{
if(n==1)
{
printf("1\n");
continue;
}
queue<LL> q;
q.push(1);
while(q.size())
{
LL t1=q.front();
LL t2;
q.pop();
t2=t1*10;
q.push(t2);
if(t2%n==0)
{
printf("%lld\n",t2);
break;
}
t2=t1*10+1;
q.push(t2);
if(t2%n==0)
{
printf("%lld\n",t2);
break;
}
}
}
return 0;
}
打表
#include<iostream>
#include<cstdio>
using namespace std;
int h[100];
long long fun(int x)
{
int i=0;
while((x/2)!=0)
{
h[i]=x%2;
i++;
x/=2;
}
h[i]=x;
long long sum=0;
for(int j=i;j>=0;j--)
sum=sum*10+h[j];
return sum;
}
int main()
{
long long n;
while(~scanf("%lld",&n))
{
if(n==0) break;
for(int i=1;;i++)
{
long long res=fun(i); //对于每个可能的数,都将其先转化为2进制,看其能否被n整除 比如20 4的2进制100刚好能将其整除
if(res%n==0)
{
printf("%lld\n",res);
break;
}
}
}
return 0;
}
本文来自博客园,作者:斯文~,转载请注明原文链接:https://www.cnblogs.com/zhiweb/p/15483315.html

浙公网安备 33010602011771号