• dfs


    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

    题意 : 对于给定的一个数 , 输出的一个数是他的倍数,并且十进制位只有 0 和 1

    思路 : DFS 和 BFS 都可以做
      bfs 的代码
    #define ll unsigned long long
    
    int n;
    void bfs(){
        queue<ll>que;
        que.push(1);
        
        while(!que.empty()){
            ll a = que.front();
            que.pop();
            
            if (a % n == 0) {
                printf("%lld
    ", a);
                break;
            }
            que.push(a*10);
            que.push(a*10+1);
        }
    }
    
    int main() {
     
        while(~scanf("%d", &n) && n){
            bfs();
        }
        //for(int i = 1; i <= 200; i++){
            //n = i;
            //bfs();
        //}
        return 0;
    }
    

      而用dfs 做 , 考虑好递归结束的条件,如果这题用 long long 的话就直接 wa 了,有些时候要想想 unsigned 的强大地方可以对长整型变量的精度增加一位。

    dfs 的代码 :

      

    #define ll unsigned long long
    ll n;
    int sign;
    
    void dfs(ll num, int cnt){
        if (cnt > 19 || sign) return;
        if (num % n == 0) {
            printf("%lld
    ", num);
            sign = 1;
            return;  // 递归函数里要写 return , 不能写 break     
        }
        dfs(num*10, cnt+1);
        dfs(num*10+1, cnt+1);
    }
    
    int main() {
     
        while(~scanf("%lld", &n) && n){
            sign = 0;
            dfs(1, 1);
        }
        return 0;
    }
    


    东北日出西边雨 道是无情却有情
  • 相关阅读:
    域名、主机名、网站名以及 URL 基础概念
    c# oracle 数据库连接以及参数化查询
    c# 委托(Func、Action)
    xcode pod install 安装失败,提示缺少文件
    一个服务器的IIS只能绑定一个HTTPS也就是443端口
    APP UI设计及切图规范
    Day7 字符串和常用数据结构
    Day6 函数和模块的使用
    Day5 练习
    python 疑难杂症
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/7738446.html
Copyright © 2020-2023  润新知