1. 程式人生 > >POJ 1426 Find The Multiple(bfs)

POJ 1426 Find The Multiple(bfs)

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

2
6
19
0

Sample Output

10
100100100100100100
111111111111111111

Source

題意:給出一個整數n,(1 <= n <= 200)。求出任意一個它的倍數m,要求m必須只由十進位制的’0’或’1’組成。m第一個數字必須是1,且n不大於200,m不超過100個十進位制數字。

題解:搜尋,佇列都可以的,但是一定不要忘記將佇列清空。

#include<iostream>//佇列程式碼
#include<queue>
using namespace std;
#define ll long long
ll n;
queue<ll>q;
void bfs()
{
    q.push(1);//從1開始
    while(!q.empty()){
    ll front=q.front();
    if(front%n==0)
    {
        cout<<front<<endl;
        return ;
    }
    q.pop();
    for(int i=0;i<2;i++)
    {
        ll x=front*10+i;
        if(x%n==0)
        {
            cout<<x<<endl;
            return ;
        }
        q.push(x);
    }
    }
}
int main()
{
    while(cin>>n&&n)
    {
        while(!q.empty()){
            q.pop();}
        bfs();
    }
    return 0;
}
#include <iostream>//搜尋
#include <algorithm>
#include <cstdio>
using namespace std;
int n,m;
queue <long long> q;
void bfs()
{
    q.push(1);
    while(!q.empty())
    {
        long long t=q.front();
        q.pop();
        if(t%n==0)
        {
            cout<<t<<endl;
            return ;
        }
        q.push(t*10);
        q.push(t*10+1);
    }
    return ;
}
int main()
{
    while(cin>>n&&n)
    {
        while(!q.empty())
        {
            q.pop();
        }
        bfs();
    }
    return 0;
}