堆优化的Dijkstra

#include <iostream>
#include <queue>
using namespace std;

const int N = 100010;
//first存储距离 second 存储节点 
typedef pair<int ,int> PII;
//用邻接表来存储稀疏图
//用优先队列来优化每次找最短的那个节点 

int n,m;//n表示节点个数 m表示边的个数 
int Head[N],Weight[N],Value[N],Next[N],Index;//数组模拟的邻接表 
bool S[N];//是否已经求了最短距离 
int Dis[N];//存储最短距离 

//邻接表插入边 
void Add(int nStart, int nEnd, int nWeight)
{
	Weight[Index] = nWeight;
	Value[Index] = nEnd;
	Next[Index] = Head[nStart];
	Head[nStart] = Index;
	Index++;
}

void Dijkstra()
{
	//初始化Dis数组 
	fill(Dis,Dis+N,0x3f3f3f3f);
	//定义优先队列  
	priority_queue<PII,vector<PII>,greater<PII> >Heap;
	Heap.push(make_pair(0,1));
	Dis[1] = 0;
	
	while(Heap.size())
	{
		int ver = Heap.top().second;
		int distance = Heap.top().first;
		Heap.pop();
		
		//如果这个点已经被加入到S中 
		if(S[ver])
		{
			continue;	
		}
		S[ver] = true;
		
		for(int i = Head[ver]; i != -1; i = Next[i])
		{
			int j = Value[i];
			if(Dis[j] > distance + Weight[i])
			{
				Dis[j] = distance + Weight[i];
				Heap.push(make_pair(Dis[j],j));
			}
		} 
	}
} 

int main(int argc, char** argv) 
{
	fill(Head,Head+N,-1);
	scanf("%d%d",&n,&m);
	
	while(m--)
	{
		int nStart,nEnd,nWeight;
		scanf("%d%d%d",&nStart,&nEnd,&nWeight);
		Add(nStart,nEnd,nWeight);
	}
	
	Dijkstra();
	
	for(int i = 1; i <= n; i++)
	{
		cout<<Dis[i]<<" ";	
	} 
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值