萌新求助,dijstra,#5TLE,其它AC
查看原帖
萌新求助,dijstra,#5TLE,其它AC
310773
PCCP楼主2022/11/4 15:29

RT,只有#5TLE了,不知道有什么问题。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<long long ,int> PLI;
const int N=3e5+10;
int n,m;
int he[N<<1],ne[N<<1],to[N<<1],tot=0;
long long w[N<<1],dist[N];
bool st[N];
void addedge(int x,int y,long long z){
	for(int i=he[x];i;i=ne[i]){
		if(to[i]==y){
			w[i]=min(w[i],z);
			return ;
		}
		else{
			continue;
		}
	}
	to[++tot]=y;
	ne[tot]=he[x];
	he[x]=tot;
	w[tot]=z;
	return ;
}
void dijst(){
	priority_queue<PLI,vector<PLI>,greater<PLI> > q;
	memset(st,0,sizeof st);
	memset(dist,0x3f,sizeof dist);
	dist[1]=0;
	q.push({0,1});
	while(q.size()){
		PLI t=q.top();
		q.pop();
		if(st[t.second]==1){
			continue;
		}
		st[t.second]=1;
		for(int i=he[t.second];i;i=ne[i]){
			int v=to[i];
			if(dist[v]>t.first+w[i]){
				dist[v]=t.first+w[i];
				q.push({dist[v],v});
			}
		}
	}
}
int main(){
	scanf("%d%d",&n,&m);
	int x,y;
	long long z;
	for(int i=1;i<=m;i++){
		scanf("%d%d%lld",&x,&y,&z);
		if(x==y){
			continue;
		}
		addedge(x,y,z);
	}
	dijst();
	for(int i=1;i<=n;i++){
		if(dist[i]>=0x3f3f3f3f3f3f3f3f){
			printf("-1 ");
		}
		else{
			printf("%lld ",dist[i]);
		}
	}
}
2022/11/4 15:29
加载中...