题目链接:http://poj.org/problem?id=1426
题目大意:给定n,求出只含0,1的十进制数m是n的倍数
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
思路:容易被题目误导,题目说m位数不超过100位,就以为会超过long long,然而答案是不会超过long long的,所以可以直接bfs。
代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
#define FOU(i,x,y) for(int i=x;i<=y;i++)
#define FOD(i,x,y) for(int i=x;i>=y;i--)
#define MEM(a,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)
const double EXP = 1e-9;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const ll MINF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9+7;
const int N = 1e6+5;
ll n,x,ans;
void bfs()
{
queue<ll>q;
q.push(1);
while(!q.empty())
{
x=q.front();
q.pop();
if(x%n==0)
{
ans=x;
return ;
}
q.push(x*10);
q.push(x*10+1);
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
//std::ios::sync_with_stdio(false);
while(~scanf("%lld",&n))
{
if(n==0)
break;
else
{
bfs();
printf("%lld\n",ans);
}
}
return 0;
}
我最开始以为会超longlong,所以写了一份超时的字符串处理代码,虽然超时,但n小于等于200,所以可以用来打表,也相当于ac代码吧(--滑稽
附上代码:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
const double EXP = 1e-9;
typedef long long ll;
const int INF = 0x3f3f3f;
int mod;
string ans;
int n;
string result[205];
int pow_mod(int a,int b)
{
if(b==0)
return 1;
else
{
int ans=1;
while(b)
{
if(b&1)
{
ans=(ans*a)%mod;
}
a=(a*a)%mod;
b>>=1;
}
return ans;
}
}
bool check(string s)
{
int cnt=0;
int res=0;
int len=s.size();
for(int i=len-1;i>=0;i--)
{
int temp=pow_mod(10,cnt);
res=(res+((s[i]-'0')*temp)%mod)%mod;
cnt++;
}
return res==0;
}
void bfs()
{
queue<string>q;
q.push("1");
string a,next;
while(!q.empty())
{
a=q.front();
q.pop();
if(check(a))
{
ans=a;
return ;
}
next=a+"1";
q.push(next);
next=a+"0";
q.push(next);
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
for(int i=1;i<=200;i++)
{
n=i;
mod=n;
bfs();
result[i]=ans;
}
std::ios::sync_with_stdio(false);
while(cin>>n)
{
if(n==0)
break;
cout<<result[n]<<endl;
}
return 0;
}