求助,马蜂良好

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

_3145114514_ @ 2024-06-10 17:40:08

只 AC #5 ,其他全WA,调不出来

#include <bits/stdc++.h>
const int maxn = 1000005;
using namespace std;
const int inf = 2147483647;
int n, m, s, cnt;
int dis[maxn], h[maxn], to[maxn], val[maxn], nxt[maxn];
bool vis[maxn];
struct node
{
    int v, w;
    friend bool operator<(node a, node b)
    {
        return a.w < b.w;
    }
} tmp;

priority_queue<node> q;
void dijkstra()
{
    for (int i = 1; i <= n; i++)
    {
        dis[i] = inf;
    }
    dis[s] = 0;
    tmp.v = s, tmp.w = 0;
    q.push(tmp);
    while (!q.empty())
    {
        int u = q.top().v;
        q.pop();
        if (vis[u])
            continue;
        vis[u] = 1;
        for (int i = h[u]; i; i = nxt[i])
        {
            if (dis[to[i]] > (long long)dis[u] + val[i])
            {
                dis[to[i]] = dis[u] + val[i];
                tmp.w = dis[to[i]], tmp.v = to[i];
                q.push(tmp);
            }
        }
    }
}
void add(int a, int b, int c)
{
    to[++cnt] = b;
    val[cnt] = c;
    nxt[cnt] = h[a];
    h[a] = cnt;
}

int main()
{
    scanf("%d%d%d", &n, &m, &s);
    for (int i = 1, u, v, w; i <= m; i++)
    {
        scanf("%d%d%d", &u, &v, &w);
        add(u, v, w);
    }
    dijkstra();
    for (int i = 1; i <= n; i++)
    {
        printf("%d ", dis[i]);
    }
    //system("pause");
    return 0;
}

by forgotmyhandle @ 2024-06-10 17:43:34

priority_queue 默认从大到小,所以你比较函数不等号写反了


by forgotmyhandle @ 2024-06-10 17:44:05

@3145114514


by forgotmyhandle @ 2024-06-10 17:45:04

我指的是你自定义小于号函数体里那个应该是 >


by masonxiong @ 2024-06-10 18:00:20

@3145114514

node 的运算符重载中应当把 return a.w < b.w 改成 return a.w > b.w


by _3145114514_ @ 2024-06-10 20:16:27

好了,谢谢大佬


by _3145114514_ @ 2024-06-10 20:17:05

@forgotmyhandle @masonxiong


|