求助,48分,dijkstra 堆优化,c++, 超时
查看原帖
求助,48分,dijkstra 堆优化,c++, 超时
928417
gogododone楼主2023/2/5 20:55

使用的是优先队列,但是 #2 #3 #6 case 超时了。。。

有大佬能帮忙分析下哪里耗时了嘛?

感谢感谢~~

代码如下:

    #include <iostream>
    #include <vector>
    #include <queue>
    using namespace std;

    #define MAXN 500001
    #define INF ((1<<31)-1)

    int VERTEX;
    int EDGE;
    struct Edge
    {
        int to, w, next;
    };

    Edge edges[MAXN];
    int head[MAXN], cnt;

    void addEdge(int from, int to, int w)
    {
        edges[++cnt].to = to;
        edges[cnt].w = w;
        edges[cnt].next = head[from];
        head[from] = cnt;
    }

    void dijkstra(int start, vector<int>& dist)
    {
        dist[start] = 0;

        vector<int> visited(VERTEX+1, 0);

        priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> _q;
        _q.push({dist[start],start});

        while (!_q.empty())
        {
            int minDist = _q.top().first;
            int from = _q.top().second;
            _q.pop();

            visited[from] = 1;

            for (int e=head[from]; e; e=edges[e].next)
            {
                int to = edges[e].to;
                int w = edges[e].w;
                if (!visited[to] && dist[to] > dist[from] + w)
                {
                    dist[to] = dist[from] + w;
                    _q.push({dist[to], to});
                }
            }
        }
    }

    int main()
    {
        int start;
        scanf("%d%d%d", &VERTEX, &EDGE, &start);
        for (int i=1; i<=EDGE; i++)
        {
            int from, to, w;
            scanf("%d%d%d", &from, &to, &w);
            addEdge(from, to, w);
        }
        vector<int> dist(VERTEX+1, INF);
        dijkstra(start, dist);
        for (int i=1; i<=VERTEX; i++)
            printf("%d ", dist[i]);
        printf("\n");
        return 0;
    }

2023/2/5 20:55
加载中...