题意:一个小船在海上航行,海面上是一个n*m的矩阵,每个点都有一个洋流,小船顺着洋流走,不消耗能量,其他则消耗一个能量,给出始点和终点,求最小能量消耗
分析:求最少消耗,bfs,每次取出能量消耗最少的,vis数组记录到达每个点最小消耗的能量,如果新的走法到某点,消耗能量要少,则更新vis,加入队列,很简单,见代码
#include<cstdio> #include<queue> #include<cstring> #include<algorithm> #include<iostream> using namespace std; const int maxn=1005; const int INF=0x3f3f3f3f; char G[maxn][maxn]; int sx,sy,ex,ey,n,m,t; int vis[maxn][maxn]; struct node{ int x,y,v; node(int a,int b,int c):x(a),y(b),v(c){} bool operator < (const node& r) const{ return v>r.v; } void read(){ scanf("%d%d",&x,&y); } }; const int dx[]={-1,-1,0,1,1,1,0,-1}; const int dy[]={0,1,1,1,0,-1,-1,-1}; priority_queue<node> q; void bfs(){ while(!q.empty()){ node e=q.top();q.pop(); if(e.x==ex&&e.y==ey){ cout<<e.v<<endl; return ; } for(int i=0;i<8;i++){ int nx=e.x+dx[i]; int ny=e.y+dy[i]; int nv=e.v; if(nx<1||nx>n||ny<1||ny>m) continue; if(i!=(G[e.x][e.y]-'0')) nv++; if(vis[nx][ny]==-1||nv<vis[nx][ny]){ vis[nx][ny]=nv; q.push(node(nx,ny,nv)); } } } } int main(){ scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%s",G[i]+1); scanf("%d",&t); while(t--){ while(!q.empty())q.pop(); memset(vis,-1,sizeof(vis)); scanf("%d%d%d%d",&sx,&sy,&ex,&ey); vis[sx][sy]=0; q.push(node(sx,sy,0)); bfs(); } return 0; }