XDOJ1012--奇妙的旅行
2014-08-17 16:27
246 查看
Description
炸鸡儿非常喜欢旅行,而且喜欢在坐标轴上旅行,从起点A到终点B(0<=A,B<=100000)。他旅行的方法很特殊,喜欢用跳的,每次跳一个地方只有三种方法:
从点C跳到点C+1。
从点C跳到点C-1。
从点C跳到点2*C。
请问他从A跳到B至少需要多少步?
Input
每组数据两个整数A,B(0<=A,B<=100000)。
Output
每例输出一行,表示至少需要的步数。
Sample Input
1 100000
0 100000
Sample Output
21
22
解题思路:
这道题有动态规划的特点,设L(n)表示从A到n所需要的最小步数,则
L(m) = min{ L(m-1), L(m+1), L(m/2) }
但是在实际上我没能成功用其编程,最终还是用了网上的BFS实现程序。
从A开始广度搜索,最先找到B的层就是所需要的最少步数
炸鸡儿非常喜欢旅行,而且喜欢在坐标轴上旅行,从起点A到终点B(0<=A,B<=100000)。他旅行的方法很特殊,喜欢用跳的,每次跳一个地方只有三种方法:
从点C跳到点C+1。
从点C跳到点C-1。
从点C跳到点2*C。
请问他从A跳到B至少需要多少步?
Input
每组数据两个整数A,B(0<=A,B<=100000)。
Output
每例输出一行,表示至少需要的步数。
Sample Input
1 100000
0 100000
Sample Output
21
22
解题思路:
这道题有动态规划的特点,设L(n)表示从A到n所需要的最小步数,则
L(m) = min{ L(m-1), L(m+1), L(m/2) }
但是在实际上我没能成功用其编程,最终还是用了网上的BFS实现程序。
从A开始广度搜索,最先找到B的层就是所需要的最少步数
#include<iostream> #include<queue> using namespace std; struct node { int val,step; }; int S,T; const int L = 130000; bool s[130000]; int bfs() { for(int i=0;i<L;++i) s[i] = false; queue<node> q; while (!q.empty()) q.pop(); node st; st.val=S; st.step=0; q.push(st); s[S]=true; while (!q.empty()) { node st=q.front(); q.pop(); if (st.val==T) return st.step; if (st.val+1<L) if (!s[st.val+1]) { s[st.val+1]=true; node tmp=st; tmp.step++; tmp.val=st.val+1; q.push(tmp); } if (st.val-1>0) if (!s[st.val-1]) { s[st.val-1]=true; node tmp=st; tmp.step++; tmp.val=st.val-1; q.push(tmp); } if ((st.val<<1)<L) if (!s[st.val<<1]) { s[st.val<<1]=true; node tmp=st; tmp.step++; tmp.val=st.val<<1; q.push(tmp); } } } int main() { while (cin>>S>>T) { if (S>T) { cout<<S-T<<endl; continue; } int ans=bfs(); cout<<ans<<endl; } return 0; }
相关文章推荐
- 奇妙的旅行[XDU1012]
- xdoj 1012
- 旅行中的小插曲 1012
- BZOJ 1012: [JSOI2008]最大数maxnumber
- xdoj-1111
- 旅行 数论 打表找规律
- 【BZOJ 1012】【JSOI 2008】最大数maxnumber
- Codevs1036 商务旅行 LCA【pascal】
- BZOJ 1012之线段树解法
- Codevs 1036 商务旅行
- 一次奇妙的大项目维护经历(1)
- BZOJ 3531: [Sdoi2014]旅行 [树链剖分]
- 旅行售货员问题
- PAT 乙级 1012
- 洛谷1012拼数
- BZOJ3141: [Hnoi2013]旅行
- 1012. 数字分类 (20)
- PAT-B 1012. 数字分类 (20)
- 记录一次Oracle VM VirtualBox 的奇妙之旅...
- [置顶] 奇妙的数字