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解法:
给一个数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; }
相关文章推荐
- Android 工程引用其他Library工程时注意事项
- MAC ACL、RACL和VACL
- Nancy
- 测试架构师:软件架构模式之分层架构 2
- 测试架构师:软件架构模式之分层架构 1
- 设计模式之禅之设计模式-迭代器模式
- 数据恢复软件extundelete介绍
- requirejs的用法
- mutex and condition_variable[c++11]
- Solr-5.3.0学习笔记(一)基础入门
- VIM高级操作
- js处理大数据方式
- ADB server didn't ACK---3步完美解决
- centos6 Linux安装redis 2.6.14
- Java中StringBuffer类append方法的使用
- C语言 百炼成钢5
- 老李分享:webservice是什么?2
- 老李分享:webservice是什么?1
- Dom5(取消默认事件,获取分辨率,获取鼠标按钮)
- Java学习第9天(7):面向对象-内部匿名静态类