POJ 1426 (BFS + 同余定理)

来源:互联网 发布:mac book pro怎么用 编辑:程序博客网 时间:2024/06/02 20:46
Find The Multiple
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 26777 Accepted: 11097 Special Judge

Description

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

26190

Sample Output

10100100100100100100111111111111111111

Source


题意:

求只有1,0,组成的十进制数,且是所给数字n的倍数;任意输出位数不超过100的一个;


分析:

BFS是搜索当前位数字 (除最高位固定为1),因为每一位都只有0或1两种选择,换而言之是一个双入口BFS

本题难点在于搜索之后的处理:对余数的处理,对大数的处理,余数与所求倍数间的关系


同余模定理 :                               

(a*b)%n = (a%n *b%n)%n   

(a+b)%n = (a%n +b%n)%n  


前一步 (11*10+1)%6=2   即k=110 , k%6=2

当前步 (110*10+1)%6=2

由同余模定理  (110*10+1)%6 = ((110*10)%6+1%6 )%6 = ((110%6 * 10%6)%6 +1 )%6

不难发现下划线部分110%6等于 (11*10+0)%6 = 2

所以当前步(110*10+1)%6可以转变为  (2*10+1)%6=2

 

很显然地,这种处理把k=110 等价于 k=2

即用 前一步操作得到的余数 代替 当前步的k值


用c++会TLE  G++可过...

#include<iostream>#include<algorithm>#include<cstdio>#include<math.h>#include<string.h>#include<queue>typedef long long ll;using namespace std;ll BFS(ll n){    queue<ll>q;    q.push(1);    while(!q.empty())    {        ll x;        x=q.front();        q.pop();        if(x%n==0)            return x;        q.push(x*10);        q.push(x*10+1);    }    return -1;}int main(){    ll n;    while(scanf("%I64d",&n)&&n)    {        ll ans=BFS(n);        printf("%I64d\n",ans);    }    return 0;}


0 0
原创粉丝点击