涉及到unordered_set和pair以及tuple,记录一下,感觉拿DFS做会简单很多。
输入描述:
第一行为两个正整数,分别表示上述之M,N。
接下来有M行,每一行都包含N个正整数。
后面一行有两个整数,表示初始格子的行号及列号,行号范围为[0,M-1],列号范围为[0,N-1]。
最后一行有两个整数,表示目标格子的行号及列号,行号范围为[0,M-1], 列号范围为[0,N-1]。
输出描述:
若当前位置值大于等于下一步的值则不消耗能量,若小于则消耗差值的能量
求:输出最小消耗的总能量。
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
using namespace std;
struct pair_hash{
inline size_t operator()(const pair<int,int>& p) const{
return p.first * 10 + p.second;
}
};
int main(){
int m, n;
cin >> m >> n;
vector<vector<int>> dp(m, vector<int>(n));
unordered_set<pair<int,int>, pair_hash> set;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
cin >> dp[i][j];
}
}
int res = 10000000;
int sx,sy,ex,ey;
cin >> sx >> sy;
cin >> ex >> ey;
queue<tuple<int,int,int>> q;
q.emplace(sx,sy,0);
set.insert({sx,sy});
while(!q.empty()){
auto& [x,y,z] = q.front();
q.pop();
if(x == ex && y == ey){
res = min(res, z);
}
for(auto& d: dir){
int nx = x + d[0];
int ny = y + d[1];
if(!set.count({nx,ny}) && nx >= 0 && nx < m && ny >= 0 && ny < n){
q.emplace(nx, ny, dp[x][y] >= dp[nx][ny] ? z : z + (dp[nx][ny] - dp[x][y]));
set.insert({nx,ny});
}
}
}
cout << res;
return 0;
}