这道题如何优化到底?

P4779 【模板】单源最短路径(标准版)

SwethessPotion @ 2024-07-08 21:26:15

玄关求助,第三个点死活过不去,1.05s。。。

#include <bits/stdc++.h>
#define INTINF 2147483647
#define LLINF 9223372036854775807
typedef long long ll;
using namespace std;

const int N = 1e5 + 10;
int n, m, s;
vector<pair<int, int> > graph[N];
bool f[N];
int dis[N];
struct pii
{
    int first, second;
    friend bool operator >(const pii a, const pii b) {return a.first > b.first;}
};

priority_queue<pii, vector<pii>, greater<pii> > q;

inline void dijkstra()
{
    for (int i = 1; i <= n; i++)
        dis[i] = 1e9 + 10;

    dis[s] = 0;
    q.push({0, s});

    while (!q.empty())
    {
        int id = q.top().second;
        f[id] = true;
        q.pop();
        for (auto j: graph[id])
        {
            if (dis[j.first] > dis[id] + j.second)
            {
                dis[j.first] = dis[id] + j.second;
                q.push({dis[j.first], j.first});
            }
        }
    }
}

int main()
{
    scanf("%d %d %d", &n, &m, &s);
    for (int i = 1; i <= m; i++)
    {
        int u, v, w;
        scanf("%d %d %d", &u, &v, &w);
        graph[u].push_back({v, w});
    }

    dijkstra();

    for (int i = 1; i <= n; i++)
    {
        printf("%d ", dis[i]);
    }
    return 0;
}

by dengchengyu @ 2024-07-08 21:31:09

你的 dijkstra 假了。 应该改成:

int id = q.top().second;
q.pop();
if(f[id])continue;
f[id] = true;

by ikunTLE @ 2024-07-08 22:29:12

快读1.02s寄了


by SwethessPotion @ 2024-07-09 08:12:14

已关@dengchengyu 太谢谢了


by SwethessPotion @ 2024-07-09 21:14:52

什么毒瘤数据啊。。。。。


|