您的位置:首页 > 其它

poj 1426 Find The Multiple

2016-01-21 16:33 417 查看
题意:

给一个数n,让你找出一个只有1,0,组成的十进制数,要求是找到的数可以被n整除。

做法:

假如n=6;

1余n=1;

10余n=1*10%6=4;

11余n=(1*10+1)%6=5;

100余n=4*10%6=4;

101余n=(4*10+1)%6=5;

110余n=5*10%6=2;

111余n=(5*10+1)%6=3;

可以看出 从1到10和11为1*10和1*10+1,从10到100和101为10*10和10*10+1,所以通过上个数字n可以得到下一个数字为n*10和n*10+1。

bfs解法:

#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
void bfs(int n)
{
queue<long long>q;
q.push(1);
while(!q.empty())
{
int i;
long long x;
x=q.front();
q.pop();
if(x%n==0)
{
printf("%lld\n",x);
return ;
}
q.push(x*10);
q.push(x*10+1);
}
}
int main()
{
int n;
while(~scanf("%d",&n)&&n)
{
bfs(n);
}
return 0;
}
dfs解法:

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
bool found;
void DFS(unsigned __int64 t ,int n,int k)
{
if(found)
return ;//如果已经发现了答案就没搜的必要了
if(t%n==0)
{
//发现答案,输出,标记变量该true
printf("%I64u\n",t);
found=true;
return ;
}
if(k==19)//到第19层,回溯
return ;
DFS(t*10,n,k+1);    //搜索×10
DFS(t*10+1,n,k+1);    //搜索×10+1
}
int main()
{
int n;
while(cin>>n,n)
{
found=false;//标记变量,当为true代表搜到了题意第一的m
DFS(1,n,0);    //从1开始搜n的倍数,第三个参数代表搜的层数,当到第19层时返回(因为第20层64位整数存不下)
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: