zhaoxibo @ 2022-07-31 19:32:00
第一次写二叉堆优化dijkstra
求助大佬
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
struct sd{
int from;
int to;
int value;
int next;
}edge[200010];
int head[100010],tot;
int dis[100010];
int heap[100010],len;
int number[100010];//结点所对堆编号
void add(int X,int Y,int Z){
edge[++tot].from=X;
edge[tot].to=Y;
edge[tot].value=Z;
edge[tot].next=head[X];
head[X]=tot;
}
void delet(int x){
if((x<<1)>len){
return ;
}
if(dis[heap[x<<1]]<dis[heap[(x<<1)|1]]&&dis[heap[x<<1]]<dis[heap[x]]){
heap[x]=heap[x<<1];
swap(heap[x],heap[x<<1]);
number[heap[x<<1]]=x<<1;
number[heap[x]]=x;
delet(x<<1);
}
else if(dis[heap[x<<1]]>=dis[heap[(x<<1)|1]]&&dis[heap[(x<<1)|1]]<dis[heap[x]]){
heap[x]=heap[(x<<1)|1];
swap(heap[x],heap[(x<<1)|1]);
number[heap[(x<<1)|1]]=(x<<1)|1;
number[heap[x]]=x;
delet((x<<1)|1);
}
return ;
}
void change(int x){
int y=number[x];
while(y>1&&dis[x]<dis[heap[y>>1]]){
swap(heap[y>>1],heap[y]);
number[heap[y]]=y;
number[heap[y>>1]]=y>>1;
y>>=1;
}
}
void dijkstra(int n,int s){
while(len>0){
int x=heap[1];
number[heap[1]]=0;
heap[1]=heap[len];
number[heap[1]]=1;
heap[len]=0;
len--;
delet(1);
for(int j=head[x];j;j=edge[j].next){
int y=edge[j].to,z=edge[j].value;
if(dis[x]+z<dis[y]){
dis[y]=dis[x]+z;
if(number[y]>0)
change(y);
else{
heap[++len]=y;
int num=len;
number[y]=num;
while(num>1&&dis[heap[num]]<dis[heap[num>>1]]){
swap(heap[num>>1],heap[num]);
number[heap[num]]=num;
number[heap[num>>1]]=num>>1;
num>>=1;
}
}
}
}
}
}
int main(){
int n,m,s;
scanf("%d%d%d",&n,&m,&s);
int x,y,z;
for(int i=0;i<=n;i++){
dis[i]=1e9;
heap[i]=1e9;
}
dis[s]=0;
for(int i=1;i<=m;i++){
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
if(x==s){
dis[y]=min(dis[y],z);
heap[++len]=y;
int num=len;
number[y]=num;
while(num>1&&dis[heap[num]]<dis[heap[num>>1]]){
swap(heap[num>>1],heap[num]);
number[heap[num]]=num;
number[heap[num>>1]]=num>>1;
num>>=1;
}
}
}
dijkstra(n,s);
for(int i=1;i<=n;i++) printf("%d ",dis[i]);
}
by NightTide @ 2022-07-31 19:49:21
@zhaoxibo 手写堆啊。%%%。你似乎没有加 vis 数组呢。
by zhaoxibo @ 2022-07-31 20:16:52
@降魔大圣 感谢,但是似乎不是这里的问题,还是WA了4个点