1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include<iostream> #include<queue> #include<string.h> using namespace std; int h[N],e[N],ne[N],w[N],idx; int n,m,s; void add(int a,int b,int c){ e[idx]=b; w[dix]=c; ne[a]=h[a]; h[a]=idx++; }
void dijkstra(){ memset(dist,0x3f,sizeof(dist)); priority_queue<PII,vector<PII>,greater<PII>> heap; heap.push({0,s}); dist[s]=0;
while(heap.size()){ int t=heap.top(); heap.pop();
int distance=t.first,ver=t.second;
if(st[ver])continue;
st[ver]=true;
for(int i=h[ver];i!=-1;i=ne[i]){ int j=e[i],c=w[i]; if(dist[j]>distance+c){ dist[j]=distance+c; heap.push({dist[j],j}); } } } } int main(){ memset(h,-1,sizeof(-1)); cin>>n>>m>>s; int a,b,c; while(m--){ cin>>a>>b>>c; add(a,b,c); } dijkstra();
for(int i=1;i<=n;i++){ cout<<dist[i]<<" "; }
return 0; }
|