数字对(高级版)
这道题目与抓牛类似,可以用bfs来解决。
细节:
1.记录step
1 np.step=op.step+1;
2.扩展
这里不同于其他题目,但只要按题意来写就不会有问题。
👇
(一) 1 np.x=op.x+op.y; 2 np.y=op.y;
(二) 1 np.x=op.x; 2 np.y=op.x+op.y;
3.剪枝
这是一个重点,如果不用会爆。
内存

......
像(7001,1),(50,1)这样的废数都有个特点:他俩的相差很大,这里就可以剪枝了。
👇
(一) 1 np.x<np.y*3.45
(二) 1 np.y<np.x*3.45
程序:
#include<bits/stdc++.h> using namespace std; int n; struct point{ int x; int y; int step; }; queue <point> q; void bfs(point s) { q.push(s); while(q.size()) { point op=q.front(); q.pop(); if(op.x==n||op.y==n) { cout<<op.step-1; return; } point np; np.x=op.x+op.y; np.y=op.y; if(np.x<=n&&np.x<np.y*3.45) { np.step=op.step+1; q.push(np); } np.x=op.x; np.y=op.x+op.y; if(np.y<=n&&np.y<np.x*3.45) { np.step=op.step+1; q.push(np); } } } int main() { cin>>n; point s; s.x=1; s.y=1; s.step=1; bfs(s); return 0; }

浙公网安备 33010602011771号