POJ-1426-Find The Multiple(DFS)

穿精又带淫゛_ 提交于 2020-02-10 20:23:25

Find The Multiple

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

思路:
题目要求输入一个数,n,寻求一个数x,使x,只由0和1组成,位数不超过十八位,并且是输入数的倍数。由题知输出数是long long型的,可以用搜索dfs,每次搜 x*10 、 x *10+1 从而保证输入数只由0和1,同时注意若输入是0或者是输出数超过十八位的,直接return。

完整代码:

/**
    样例不对,但是AC了,好奇怪
*/
#include<iostream>
#include<cstdio>
using namespace std;
int n,m;
void dfs(long long x,int len)
{
    if(m||len>18)
    {
        return ;
    }
    if(x%n==0)
    {
        m=1;
        cout<<x<<endl;
        return ;
    }
    dfs(x*10,len+1);
    dfs(x*10+1,len+1);
}
int main()
{
    while(cin>>n)
    {
        if(n==0)
        {
            break;
        }
        m=0;
        dfs(1,0);
    }
    return 0;
}

原题链接:
https://vjudge.net/problem/POJ-1426
http://poj.org/problem?id=1426

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!