【POJ - 1426】Find The Multiple(dfs)


-->Find The Multiple

原文是英語,直接上中文了

Descriptions:

給定一個正整數n,請編寫一個程序來尋找n的一個非零的倍數m,這個m應當在十進制表示時每一位上只包含0或者1。你可以假定n不大於200且m不多於100位。 
提示:本題采用Special Judge,你無需輸出所有符合條件的m,你只需要輸出任一符合條件的m即可。

Input

輸入包含多組數據,每組數據僅一行,只包含一個正整數n (1 <= n <= 200).

Output

對於輸入的每組n,都輸出任一符合條件的m。即使有多個符合條件的m,你也只需要輸出一個即可。

Sample Input

2
6
19
0

Sample Output

10
100100100100100100
111111111111111111

題目鏈接:

https://vjudge.net/problem/POJ-1426

所求得的數只含有1或0,所以從1開始深搜,兩個方向(n * 10) 或者(n * 10+1)。dfs終止條件:找到那個數或者這個數的長度大於19。 至於為何要大於19,很簡單,long long最大值就是19位

AC代碼

#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#define mod 1000000007
#define eps 1e-6
#define ll long long
#define INF 0x3f3f3f3f
#define MEM(x,y) memset(x,y,sizeof(x))
#define Maxn 110
using namespace std;
int n,flag;
void dfs(int step,long long y)//step為數的長度,y為要尋找的數
{
    if(step>19 || flag==1)//利用flag保證找到這個數的時候終止
        return;
    if(y%n==0)
    {
        flag=1;
        cout << y << endl;
        return;
    }
    dfs(step+1,y*10);//兩個方向
    dfs(step+1,y*10+1);
}
int main()
{
    while(cin >> n)
    {
        if(n==0)
            break;
        flag=0;
        dfs(1,1);//從1開始深搜,初始階段長度為1
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM