【悬关】Dijkstra模板求助,样例过了TLE 0pts

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

Literally114514 @ 2023-10-01 10:06:32

link

#include <iostream>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
int n,m,u,minn=2147483647,nextadd,p;
struct s{
    int v,w;
};
s temp;
queue <int> S;
vector <s> map[100010];
int dist[100010];
bool used[100010];
int main(){
    memset(dist,11451400,sizeof(dist));
    cin>>n>>m>>p;
    for(int i=1;i<=m;i++){
        cin>>u>>temp.v;
        cin>>temp.w;
        map[u].push_back(temp);
    }
    S.push(1);
    while(S.size()<n){
        minn=2147483647;
        used[S.back()]=1;
        if(S.back()==1){
            for(int i=0;i<map[1].size();i++){
                dist[map[1][i].v]=map[1][i].w;
            }
        }else{
            for(int i=0;i<map[S.back()].size();i++){
                if((dist[S.back()]+map[S.back()][i].w) < (dist[map[S.back()][i].v]) ){
                    dist[map[S.back()][i].v] = (dist[S.back()]+map[S.back()][i].w);
                }
            }
        }   
        for(int i=1;i<=n;i++){
            if(dist[i]<=minn && used[i]==0){
                minn=dist[i];
                nextadd=i;
            }
        }
        S.push(nextadd);
    }
    cout<<0<<' ';
    for(int i=2;i<=n;i++) cout<<dist[i]<<' ';
}

by DFSer @ 2023-10-01 10:11:33

用优先队列啊,这题裸的dijkstra过不了


by Literally114514 @ 2023-10-01 10:16:56

@DFSer @YTY ok


by Gary_NotFound @ 2023-10-01 10:18:26

真的没见过不写优化堆的...


by zjh114514 @ 2023-10-01 10:20:43

dist初始化太小了


by Literally114514 @ 2023-10-01 10:23:50

@Gary_NotFound 没学过……


by Literally114514 @ 2023-10-01 10:24:46

@zjh114514 没小吧 n<=10^5


by _YTY_ @ 2023-10-01 10:28:55

我评论呢

补发:加堆优化


by zjh114514 @ 2023-10-02 09:34:07

@Literally n<=1e5 不代表到那里的最短路<=1e5啊,\sum w<=1e9


|