poj 1426 Find The Multiple

    xiaoxiao2021-04-16  219

    Find The Multiple

    Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 49001 Accepted: 20448 Special Judge 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

    2 6 19 0 Sample Output

    10 100100100100100100 111111111111111111

    这题题目可能有些同学看不懂吧,这题说的意思是:找一个只由1,0组成的数,对于给定的n,能够整除这个数。 这题思路很简单,深搜和广搜代码都简短。由于由1,0组成,故只需在原来基础上10或10+1就可使数只由1,0组成。 直接上代码:

    BFS

    #include <iostream> #include <queue> using namespace std; typedef __int64 ll; void bfs(int n) { ll s = 1; queue<ll> q; q.push(s); while(!q.empty()) { ll sum = q.front(); q.pop(); if(sum % n == 0) { cout << sum << endl; return; } q.push(sum*10); q.push(sum*10+1); } } int main() { int n; while(cin >> n && n) { bfs(n); } return 0; }

    DFS

    #include <iostream> #include <cstdio> #include <cstring> using namespace std; int n; int solve;//标记量,在递归中,如果solve为1了,说明之前已经找到了符合条件的不用继续递归下去了 void DFS(long long num,int k){ if(solve==1)return; if(num%n==0){ printf("%ll\n",num); solve = 1; return; } if(k==19)return;//题目要求不超100位,如果没有这句话可能会一直递归下去,直到溢出 DFS(num*10,k+1); DFS(num*10+1,k+1); } int main(){ while(~scanf("%d",&n)&&n){ solve = 0; DFS(1,0);//深搜从1开始 } return 0; }

    还有一种思路是通过数组来写,因为每次都对一个数操作两次,故后来的数的数组下标是之前数的下标的两倍,故可根据此来写

    #include <iostream> #include <cstdio> #include <cstring> using namespace std; long long mod[1000000]; int main(){ int n; while(~scanf("%d",&n)&&n){ int i; for(i = 1;; i++){//这里要从一开始,为什么看下面 mod[i] = mod[i/2]*10+i%2; //这里就巧妙用到下标奇偶性质,奇数模2为1,就相当与加一,而偶数相当于不加,所以下标从1开始是方便的, if(mod[i]%n==0){ printf("%lld\n",mod[i]); break; } } } return 0; }

    最新回复(0)