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

题目描述

输入格式
第一行为三个正整数 n, m, s,m 第二行起 m行,每行三个非负整数
的有向边。
输出格式
输出一行 nn 个空格分隔的非负整数,表示 ss 到每个点的距离。
输入输出样例
输入
4 6 1
1 2 2
2 3 2
2 4 1
1 3 5
3 4 3
1 4 4
输出
0 2 4 3
这道题卡掉了SPFA 的测试点,所以我用了堆优化版的dijkstra

#include<bits/stdc++.h>
using namespace std;

const int N=1e6+10;
int n,m,s;
int h[N] , w[N] , e[N] , ne[N] , idx;
int dist[N];
bool st[N];  //判断是否已经在队列之中;
typedef pair<int,int> PII;
 
void add(int a,int b,int c)
{
	e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
void dijkstra()
{
	memset(dist,0x3f,sizeof dist);
	dist[s]=0;
	priority_queue<PII,vector<PII>,greater<PII>>  heap;
	heap.push({0,s});  //将s号点的距离设置为1,这个顺序不能颠倒;
	while(heap.size())
	{
		PII t=heap.top();
		heap.pop();
		int ver=t.second,distance=t.first;
		if(st[ver])	continue;
		st[ver]=true;
		for(int i=h[ver];i!=-1;i=ne[i])
		{
			int j=e[i];
			if(dist[j]>dist[ver]+w[i])
			{
				dist[j]=dist[ver]+w[i];
				heap.push({dist[j],j}); 
			}
		}
	}
}
int main()
{
	int a,b,c;
	cin>>n>>m>>s;
	memset(h,-1,sizeof h);
	for(int i=0;i<m;i++)
	{
		cin>>a>>b>>c;
		add(a,b,c);
	}
	dijkstra();
	for(int i=1;i<=n;i++)
		cout<<dist[i]<<" ";
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值