1562: PUBG
时间限制: 1 Sec 内存限制: 128 MB
就是求单源最短路,迪杰斯特拉算法
#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const int maxn = 1e2 + 10;
int d[4][2] = {-1, 0, 1, 0, 0, -1, 0, 1};
int sx, sy, ex, ey, n;
int ans = -1;
struct node
{
int x, y, c;
bool operator < (const node &r) const
{
return c > r.c;
}
};
bool vis[maxn][maxn];
int dist[maxn][maxn];
int m[maxn][maxn];
void dijkstra()
{
memset(vis, false, sizeof(vis));
memset(dist, 0x3f, sizeof(dist));
dist[sx][sy] = 0;
priority_queue<node> q;
q.push(node{sx, sy, 0});
while(!q.empty())
{
node tmp = q.top();
q.pop();
vis[tmp.x][tmp.y] = true;
for(int i = 0; i < 4; ++i)
{
int x = tmp.x + d[i][0];
int y = tmp.y + d[i][1];
if(x == ex && y == ey)
{
ans = tmp.c;
return;
}
if(x <= n && x >= 1 && y <= n && y >= 1 && !vis[x][y] && dist[x][y] > tmp.c + m[x][y])
{
dist[x][y] = tmp.c + m[x][y];
q.push(node{x, y, dist[x][y]});
}
}
}
}
int main()
{
while(cin >> n)
{
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= n; ++j)
{
cin >> m[i][j];
if(m[i][j] == -1)
sx = i, sy = j;
else if(m[i][j] == -2)
ex = i, ey = j;
}
}
dijkstra();
cout << ans << endl;
}
return 0;
}