Find The Multiple (深度搜索)

来源:互联网 发布:湖北省软件协会 编辑:程序博客网 时间:2024/06/04 19:09

Find The Multiple

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 20000/10000K (Java/Other)
Total Submission(s) : 31   Accepted Submission(s) : 11
Special Judge
Problem 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
PKU
 

题意:

有一个整数n,让你找一个适当的m(m只包含0和1且位数不超过100位)的整数。

思路:

一开始被100位 吓到了,因为n不大于200,其实unsigned long long完全可以找到答案,最大的都不会超过!总共有两条搜索路径,应该是目前的数字后添加个1或则0,即x*10+0或x*10+1,再将步数加一,注意unsigned __int64的范围,-(10^19)~(10^20)所以步数不能超过19次。这是很重要的一点,也是解题的关键点!

代码:

#include <iostream>#include <stdio.h>using namespace std;int n;int flag;void dfs(unsigned long long x,int k){    if(flag==1)  //有答案了,就立刻停止不在搜了    return;    if(k==19)   //超过19次不在搜了        return;    if(x%n==0)    {        cout<<x<<endl;        flag=1;        return;    }    else        dfs(x*10,k+1);        dfs(x*10+1,k+1);}int main(){    while(cin>>n)    {        if(n==0)break;        flag=0;        dfs(1,0);    }    return 0;}
心得:

此题目的关键就是unsigned long long的运用和步数的限制,才不会使问题复杂化!


原创粉丝点击