最短路问题Dij求助
查看原帖
最短路问题Dij求助
372454
AsadChen楼主2022/8/6 10:32

P6833雷雨 最短路 用的Dij算法 但是会运行时出错 连答案都不会输出出来

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>

using namespace std;

typedef long long LL;

const int N = 1010, INF = 0x3f3f3f3f;

struct Edge
{
    LL x, y, dis;
    bool operator < (const Edge & W)const
    {
        return dis > W.dis;
    }
};
LL G[N][N], dis[3][N][N];
int n, m, a, b, c;
bool vis[N][N];
int dx[4] = {0, 1, -1, 0};
int dy[4] = {1, 0, 0, -1};

void dijkstra(int k, int sx, int sy)
{
    priority_queue<Edge> q;
    q.push({sx, sy, G[sx][sy]});

    memset(vis, false, sizeof vis);
    for (int i = 1; i <= N; i++)
    {
        for (int j = 1; j <= N; j++) dis[k][i][j] = INF;
    }

    dis[k][sx][sy] = G[sx][sy];

    while (q.size())
    {
        auto now = q.top();
        q.pop();
        int nowx = now.x, nowy = now.y;

        if (vis[nowx][nowy]) continue;
        vis[nowx][nowy] = true;

        for (int i = 0; i < 4; i++)
        {
            int nx = nowx + dx[i], ny = nowy + dy[i];
            if (nx >= 1 && nx <= n && ny >= 1 && ny <= m)
            {
                if (dis[k][nx][ny] > dis[k][nowx][nowy] + G[nx][ny])
                {
                    dis[k][nx][ny] = dis[k][nowx][nowy] + G[nx][ny];
                    q.push({nx, ny, dis[k][nx][ny]});
                }
            }
        }
    }
}

int main()
{
    scanf("%d%d%d%d%d", &n, &m, &a, &b, &c);

    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            scanf("%lld", &G[i][j]);
        }
    }

    dijkstra(0, 1, a);
    dijkstra(1, n, b);
    dijkstra(2, n, c);

    LL ans = INF;
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            ans = min(ans, dis[0][i][j] + dis[1][i][j] + dis[2][i][j] - 2 * G[i][j]);
        }
    }

    printf("%lld", ans);

    return 0;
}

2022/8/6 10:32
加载中...