手写堆超时求大佬帮助
查看原帖
手写堆超时求大佬帮助
451340
夜光WAN楼主2021/4/25 16:58

用的C手写堆优化加Dijkstra超时了,请问还有救吗

#include<stdio.h>
#define inf 2147483647
struct{
	int v,w,next;
}a[500005];
struct tm{
	int v,dis;
}heap[10005];
int head[10005],size,book[10005],dis[10005];
int n,m,s;
int read()
{
	int x=0;
	char c=getchar();
	while(c<'0'||c>'9') c=getchar();
	while(c>='0'&&c<='9') x=(x<<3)+(x<<1)+c-'0',c=getchar();
	return x;
}
void swap(int a,int b){
	struct tm t;
	t=heap[a],heap[a]=heap[b],heap[b]=t;
}
void down(int x){
	int t;
	while(x<<1<=size){
		if(heap[x<<1].dis<heap[x].dis)
		t=x<<1;
		else t=x;
		if((x<<1|1)<=size&&heap[x<<1|1].dis<heap[t].dis)
		t=(x<<1|1);
		if(t!=x){
			swap(t,x);
			x=t;
		}
		else return;
	}
}
void up(int x){
	while(x>1){
		if(heap[x>>1].dis>heap[x].dis){
			swap(x,x>>1);
			x>>=1;
		}
		else return;
	}
}
void add(struct tm x){
	heap[++size]=x;
	up(size);
}
struct tm pop(){
	struct tm t=heap[1];
	swap(1,size--);
	down(1);
	return t;
}
void dij(){
	int i,t;
	struct tm in;
	for(i=1;i<=n;i++)
	dis[i]=inf;
	dis[s]=0;
	in.dis=0,in.v=s;
	add(in);
	while(size){
		t=pop().v;
		if(book[t]) continue;
		book[t]=1; 
		for(i=head[t];i;i=a[i].next){
			if(dis[a[i].v]>dis[t]+a[i].w){
				dis[a[i].v]=dis[t]+a[i].w;
				if(!book[a[i].v]){
					in.dis=dis[a[i].v],in.v=a[i].v;
					add(in);
				}
			}
		}
	}
}
int main(){
	int i,u;
	scanf("%d%d%d",&n,&m,&s);
	for(i=1;i<=m;i++){
		u=read(),a[i].v=read(),a[i].w=read();
		//scanf("%d%d%d",&u,&a[i].v,&a[i].w);
		a[i].next=head[u];
		head[u]=i;
	}
	dij();
	for(i=1;i<=n;i++)
	printf("%d ",dis[i]);
}
2021/4/25 16:58
加载中...