#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;
}
04-03
1285
09-06
1281