WA了,求调!

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

bianyanze @ 2024-10-15 19:51:08

帮助者互关 我快考CSP_J复赛了,谢谢帮助! 献上本人代码:

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
const int M=5*1e5+10;
int dis[N],n,m,vis[N],s;
int head[M],tot;
struct node{
    int to,nxt,w;
}edge[M];
int u,v,w;
void add(int u,int v,int w){
    edge[tot++]=(node){
        v,head[u],w
    };
    head[u]=tot;
}
priority_queue<pair<int,int> >q;
void dijkstra(int s){
    q.push(make_pair(0,s));
    dis[s]=0;
    while(!q.empty()){
        int u=q.top().second;
        q.pop();
        if(vis[u])continue;
        vis[u]=1;
        for(int i=head[u];i;i=edge[i].nxt){
            int v=edge[i].to,w=edge[i].w;
            if(dis[v]>dis[u]+w){
                dis[v]=dis[u]+w;
                if(!vis[v])q.push(make_pair(-dis[v],v));
            }
        }
    }
} 
int main(){

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

by Jacky29 @ 2024-10-15 19:52:02

物理意义的在旁边


by J20220912 @ 2024-10-17 09:02:23

void add(int u,int v,int w){
    edge[tot++]=(node){
        v,head[u],w
    };
    head[u]=tot;
}

改成

void add(int u,int v,int w){
    edge[++tot]=(node){
        v,head[u],w
    };
    head[u]=tot;
}

by J20220912 @ 2024-10-17 19:08:37

@bianyanze


by bianyanze @ 2024-10-19 19:42:03

why?


by sgxsz @ 2024-10-24 20:32:50

邻接表存边的编号要从1开始 如果是涉及双向边的x^1运算还要从2开始

for(int i=head[u];i;i=edge[i].nxt)

你的i就是再枚举编号,0终止 如果不想改tot其实也行,但要改for


|