首先是用结构体的
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<queue> 5 using namespace std; 6 const int maxn=200010; 7 int cnt=0, n, m, s; 8 int d[maxn], h[maxn]; 9 struct edge{ 10 int to, next, v; 11 }e[maxn*2]; 12 struct node{ 13 int val, v; 14 bool operator <(const node &b) const{ 15 return val>b.val; 16 } 17 }; 18 priority_queue<node>q; 19 void add(int x, int y, int w){ 20 e[++cnt].to=y; 21 e[cnt].v=w; 22 e[cnt].next=h[x]; 23 h[x]=cnt; 24 } 25 void dijkstra(){ 26 memset(d,0x3f,sizeof(d)); 27 d[s]=0; 28 node xx; 29 xx.val=0; 30 xx.v=s; 31 q.push(xx); 32 while(!q.empty()){ 33 int x=q.top().v; 34 int dd=q.top().val; 35 q.pop(); 36 if(dd!=d[x]) continue; 37 for(int i=h[x]; i; i=e[i].next){ 38 int y=e[i].to, z=e[i].v; 39 if(d[y]>d[x]+z){ 40 d[y]=d[x]+z; 41 node p; 42 p.val=d[y]; 43 p.v=y; 44 q.push(p); 45 } 46 } 47 } 48 } 49 int main(){ 50 scanf("%d%d%d",&n,&m,&s); 51 for(int i=1; i<=m; i++){ 52 int a, b, c; 53 scanf("%d%d%d",&a,&b,&c); 54 add(a, b, c); 55 } 56 dijkstra(); 57 for(int i=1; i<=n; i++){ 58 printf("%d ", d[i]); 59 } 60 return 0; 61 }
然后是使用stl的
#include<iostream> #include<cstdio> #include<cstring> #include<queue> using namespace std; const int maxn=200010; int cnt=0, n, m, s; int to[maxn], h[maxn], next[maxn], v[maxn]; int d[maxn], qwq[maxn]; priority_queue<pair<int, int> >q; void add(int x, int y, int w){ to[++cnt]=y; v[cnt]=w; next[cnt]=h[x]; h[x]=cnt; } void dijkstra(){ memset(d,0x3f,sizeof(d)); memset(qwq, 0, sizeof(qwq)); d[s]=0; q.push(make_pair(0,s)); while(q.size()){ int x=q.top().second; q.pop(); if(qwq[x]) continue; qwq[x]=1; for(int i=h[x]; i; i=next[i]){ int y=to[i], z=v[i]; if(d[y]>d[x]+z){ d[y]=d[x]+z; q.push(make_pair(-d[y],y)); } } } } int main(){ scanf("%d%d%d",&n,&m,&s); for(int i=1; i<=m; i++){ int a, b, c; scanf("%d%d%d",&a,&b,&c); add(a, b, c); } dijkstra(); for(int i=1; i<=n; i++){ printf("%d ", d[i]); } return 0; }
基本上两种写法时间差距并不是很大,qwq所以怎么舒服怎么来