看了题解的。。。
因为只想了BFS的思路,但是x,y的范围太大了。
BFS一定会爆空间的。
喵了看了看题解,发现还是我too young too simple~
不水了,总结题目思路:
首先题目x,y范围 10000000之内,但是只有两个点。
也就是说其中大量的跳步如果使用BFS 非常浪费,因为你只会向这个方向跳的。
(反向跳的就别说了)
所以这大量的跳步就需要我们通过一个算法来计算。
Dp?状态太大没法表示
二分?个人觉得没法套上去
IDA*? 数据大的时候大概率爆栈
…………
在看下题目的方向性:
两个点,所以跳跃只会考虑一个方向。所以需要贪心算法,只考虑x,y向另一个点跳需要几步就可以了.至于向哪个点就随便了
最后题目需要处理的是:
我们可以把一个点作为(0,0)点,另一个点往这个原点跳!
这样不仅好计算,之后BFS的也好写。
#include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <queue> struct node{ int x,y,dist; bool vis; }Point[122][122]; int sx,sy,ex,ey,ans=0; bool Can(int x,int y){ return (x>=0) && (y>=0) && (x<=100) && (y<=100); } int BFS(int x,int y){ for(int i=0;i<=100;i++) for(int j=0;j<=100;j++){ Point[i][j].x=i; Point[i][j].y=j; Point[i][j].vis=false; } static int Add[8][2] = { {-1, 2}, {1, 2}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {-2, -1}, {-2, 1} }; std::queue<node *>Q; Point[x][y].dist=0; Q.push(&Point[x][y]); while(!Q.empty()){ node *u = Q.front(); Q.pop(); if(u->vis) continue; u->vis=true; for(int i=0;i<8;i++){ int fx = u->x+Add[i][0]; int fy = u->y+Add[i][1]; if( Can(fx,fy) ){ //printf("%d %d\n",fx,fy); Point[fx][fy].dist = u->dist+1; if(fx==50 && fy==50) return Point[fx][fy].dist; Q.push(&Point[fx][fy]); } } } return -1; } int main(){ scanf("%d%d%d%d",&sx,&sy,&ex,&ey); int x = abs(sx-ex); int y = abs(sy-ey); while(x+y>=50){ if(y>x) std::swap(x,y); if(x-4>=y*2) x-=4; else x-=4,y-=2; ans+=2; } x+=50,y+=50; printf("%d\n",BFS(x,y)+ans); return 0; }