手写优先队列 1 3 4 wa ,求调试 ,必回关注 ,谢谢大佬

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

misaka2784 @ 2023-06-29 19:18:39

//
//  main.c
//  p4779
//
//  Created by yamixiu on 2023/06/29.
//

#include <stdio.h>
#include <string.h>

#define N 100010
#define M 400020
#define INF 0x3f3f3f3f3f3f3fLL

typedef long long ll;
struct v{
    int id;
    ll dis;
}vs[N];

int h[N],e[M],ne[M],idx;
ll dist[N],w[M];
struct v pi_que[M];int size;
int st[N];

void swap(struct v* a,struct v* b){
    struct v t =*a;
    *a =*b;
    *b =t;
}

ll min (ll a,ll b){return a<b?a:b;}

void push(int x,ll dis){
    pi_que[++size].id=x;
    pi_que[size].dis=dis;
    int i =size;
    while (size>1&&pi_que[i].dis<pi_que[i/2].dis) {
        swap(&pi_que[i], &pi_que[i/2]);
        i/=2;
    }
}

int pop(){
    int min = pi_que[1].id;
    int i=1;
    pi_que[1]=pi_que[size--];
    while (2*i<=size) {
        int son = 2*i;
        if(son<size&&pi_que[son].dis>pi_que[son+1].dis){son++;}
        if(pi_que[son].dis<pi_que[i].dis){swap(&pi_que[son], &pi_que[i]);i/=2;}
        else break;
    }
    return min;
}

void add(int a,int b,ll c){
    e[idx]=b;
    ne[idx]=h[a];
    w[idx]=c;
    h[a]=idx++;
}

void dijkstra(int s){
    dist[s]=0;
    push(s,dist[s]);
    while (size) {
        int u= pop();
        if(st[u])continue;
        st[u]=1;
        for(int i=h[u];i!=-1;i=ne[i]){
            int j= e[i];
            if(st[j])continue;
            if(dist[j]>dist[u]+w[i]){
                dist[j]=dist[u]+w[i];
                push(j, dist[j]);
            }
        }
    }

}

int main(int argc, const char * argv[]) {
    int n,m,s;
    scanf("%d%d%d",&n,&m,&s);
    int u,v;
    ll w;
    for(int i=1;i<=n;i++)vs[i].dis=INF;
    memset(dist, INF, sizeof(dist));
    memset(h, -1, sizeof(h));
    while (m--) {
        scanf("%d%d%lld",&u,&v,&w);
        add(u, v, w);
    }
    dijkstra(s);
    for(int i=1;i<=n;i++){
        printf("%lld ",dist[i]);}
    return 0;
}

by UnyieldingTrilobite @ 2023-06-29 19:26:20

@misaka2784

void push(int x,ll dis){
    pi_que[++size].id=x;
    pi_que[size].dis=dis;
    int i =size;
    while (i>1&&pi_que[i].dis<pi_que[i/2].dis) {
        swap(&pi_que[i], &pi_que[i/2]);
        i/=2;
    }
}

int pop(){
    int min = pi_que[1].id;
    int i=1;
    pi_que[1]=pi_que[size--];
    while (2*i<=size) {
        int son = 2*i;
        if(son<size&&pi_que[son].dis>pi_que[son+1].dis){son++;}
        if(pi_que[son].dis<pi_que[i].dis){swap(&pi_que[son], &pi_que[i]);i=son;}
        else break;
    }
    return min;
}

建议自行找不同,不懂的可以问我。


by misaka2784 @ 2023-06-29 19:27:23

@UnyieldingTrilobite 收到谢谢佬,已关注


by misaka2784 @ 2023-06-29 19:29:52

@UnyieldingTrilobite 找到了,好蠢的bug///


|