1. 程式人生 > >poj 1426 Find The Multiple(打表找範圍+搜尋)

poj 1426 Find The Multiple(打表找範圍+搜尋)

1426-Find The Multiple

題目連結http://poj.org/problem?id=1426

Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 43818   Accepted: 18368   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

Source

Dhaka 2002

【題意】輸入一個n(≤200),找到只由0、1組成的不超過100位的數能整除n並輸出,如果有多個答案,輸出一個即可。

【分析】先打表,找出範圍,發現最多也就是19位。然後就可以dfs或bfs搜尋了。知道怎麼做了就挺簡單的一道題了。

【打表程式碼】

#include<bits/stdc++.h>
using namespace std;

int check(string &s,int mod)
{
	int flag=0;
	for(int i=0;i<s.size();i++)
		flag=(flag*10+s[i]-'0')%mod;
	return flag==0;
}
string bfs(int n)
{
	queue<string>q;
	q.push("1");
	while(!q.empty())
	{
		string x=q.front();
		q.pop();
		if(check(x,n))return x;
		for(int i=0;i<2;i++)
		{
			string t=x+char('0'+i);
			if(check(t,n))return t;
			q.push(t);
		}
	}
}
int main()
{
	for(int i=1;i<=200;i++)
		cout<<bfs(i)<<endl;
	return 0;
}

【題目程式碼】dfs

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<algorithm>
using namespace std;

typedef long long ll;
int n,flag;

void dfs(int k,ll now)
{
	if(k==20 || flag)return;
	if(now%n==0)
	{
		printf("%lld\n",now);
		flag=1;
		return;
	}
	dfs(k+1,now*10);
	dfs(k+1,now*10+1);
}

int main()
{
	while(~scanf("%d",&n)&&n)
	{
		flag=0;
		dfs(1,1);
	}
	return 0;
}