dijkstra第三点TLE了,求调

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

Jadyn @ 2024-06-03 17:35:43

dijkstra代码如下

(vector存储)

#include<bits/stdc++.h>
#define N 100010
#define inf 0x3f3f3f3f
using namespace std;
struct edge{int v,w;};
vector<edge>e[N];
int d[N],vis[N],n,m,s;
priority_queue<pair<int,int> >q;
void dij(int s){
    memset(d,inf,sizeof d);
    d[s]=0;q.push({0,s});
    while(q.size()){
        int u=q.top().second;q.pop();
        if(vis[u])continue;
        vis[u]=0;
        for(auto ed:e[u]){
            int v=ed.v,w=ed.w;
            if(d[v]>d[u]+w)d[v]=d[u]+w,q.push({-d[v],v});
        }
    }
    for(int i=1;i<=n;++i)cout<<d[i]<<" ";
    return;
}
int main(){
    cin>>n>>m>>s;
    for(int i=1;i<=m;++i){
        int a,b,c;
        cin>>a>>b>>c;
        e[a].push_back({b,c});
    }
    dij(s);
    return 0;
}

评测记录


by f_hxr_ @ 2024-06-03 17:49:02

@Jadyn 第15行改成vis[u]=1


by WydnksqhbD @ 2024-06-03 18:34:33

@Jadyn

#include<bits/stdc++.h>
#define N 100010
#define inf 0x3f
using namespace std;
struct edge{int v,w;};
vector<edge>e[N];
int d[N],vis[N],n,m,s;
priority_queue<pair<int,int> >q;
void dij(int s){
    memset(d,inf,sizeof d);
    d[s]=0;q.push({0,s});
    while(q.size()){
        int u=q.top().second;q.pop();
        if(vis[u])continue;
        vis[u]=1;
        for(auto ed:e[u]){
            int v=ed.v,w=ed.w;
            if(d[v]>d[u]+w)d[v]=d[u]+w,q.push({-d[v],v});
        }
    }
    for(int i=1;i<=n;++i)cout<<d[i]<<" ";
    return;
}
int main(){
    cin>>n>>m>>s;
    for(int i=1;i<=m;++i){
        int a,b,c;
        cin>>a>>b>>c;
        e[a].push_back({b,c});
    }
    dij(s);
    return 0;
}

主要错误是 vis[u]=0; 应改为 vis[u]=1;#define inf 0x3f3f3f3f 改为 #define inf 0x3f


by Jadyn @ 2024-06-15 09:48:19

@WydnksqhbD and @fhxr非常感谢\ (。◕◡◕。)


|