zoukankan      html  css  js  c++  java
  • 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;
    }
    


    东北日出西边雨 道是无情却有情
  • 相关阅读:
    unity基础开发----Unity获取PC,Ios系统的mac地址等信息
    Web UI设计师需要了解的用栅格化系统指导网页设计
    设计网页,常见的宽度是多少像素?
    C#常用类库简介(二)
    将本地代码上传到gitLab
    删除git 分支
    git 新建分支
    将子分支代码merge到主分支master分支
    dev分支代码覆盖master分支代码
    使用flex的同时设置超出喜爱是省略号,
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/7738446.html
Copyright © 2011-2022 走看看