代码如下
#include<bits/stdc++.h> using namespace std; #define inf 1e9+7 int ct=1; int n,m; int head[200000+7]; long long dis[200000+7]; int vis[200000+7]; struct edg{ int to; int next; int w; }e[200000+7];//链式前向星 void add(int u,int v,int w)//链式前向星加边 { e[ct].to=v; e[ct].w=w; e[ct].next=head[u]; head[u]=ct++; } void djistra() { memset(vis,0,sizeof(vis)); dis[1]=0; priority_queue<pair<int,int>,vector< pair<int,int> >,greater< pair<int,int> > > heap;//堆优化 heap.push(make_pair(0,1));//pair<>存在大小关系,先看前者再看后者。 while(!heap.empty()) { int po=heap.top().second; heap.pop(); if(vis[po]) continue; vis[po]=1; for(int i=head[po];i!=0;i=e[i].next)//链式前向星遍历 { int k=e[i].to; if(dis[po]+e[i].w<dis[k]) { dis[k]=dis[po]+e[i].w; heap.push(make_pair(dis[k],k)); } } } } int main() { cin>>n>>m; memset(head,0,sizeof(head)); for(int i=1;i<=m;i++) { int x,y,z; cin>>x>>y>>z; add(x,y,z); } memset(dis,inf,sizeof(dis)); djistra(); for(int i=2;i<=n;i++) cout<<dis[i]<<endl; }
---恢复内容结束---
浙公网安备 33010602011771号