【模板】单源最短路径(标准版)
Time cost:807ms
CODE:
1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<algorithm> 5 #include<queue> 6 #define rep(i,a,n) for(int i = a;i <= n;i++) 7 #define per(i,n,a) for(int i = n;i >= a;i--) 8 #define inf 2147483647 9 #define ms(a,b) memset(a,b,sizeof(a)) 10 using namespace std; 11 typedef long long ll; 12 ll read() { 13 ll as = 0,fu = 1; 14 char c = getchar(); 15 while(c < '0' || c > '9') { 16 if(c == '-') fu = -1; 17 c = getchar(); 18 } 19 while(c >= '0' && c <= '9') { 20 as = as * 10 + c - '0'; 21 c = getchar(); 22 } 23 return as * fu; 24 } 25 const int N = 400005; 26 //head 27 int m,n,s; 28 int head[N],cst[N],nxt[N],mo[N],cnt; 29 inline void add(int x,int y,int z) { 30 mo[++cnt] = y; 31 cst[cnt] = z; 32 nxt[cnt] = head[x]; 33 head[x] = cnt; 34 return; 35 } 36 37 struct node { 38 int idx,dis; 39 bool operator < (const node &other) const { 40 return dis > other.dis; 41 } 42 }; 43 44 priority_queue<node> q; 45 int dis[N]; 46 bool vis[N]; 47 void dijkstra() { 48 ms(dis,60); 49 ms(vis,0); 50 dis[s] = 0; 51 q.push((node){s,0}); 52 while(!q.empty()) { 53 int x = q.top().idx; 54 q.pop(); 55 if(vis[x]) continue; 56 vis[x] = 1; 57 for(int i = head[x];i;i = nxt[i]) { 58 int sn = mo[i]; 59 //if(vis[sn]) continue; 60 if(dis[sn] > dis[x] + cst[i]) { 61 dis[sn] = dis[x] + cst[i]; 62 q.push((node){sn,dis[sn]}); 63 } 64 } 65 } 66 return; 67 } 68 69 70 int main() { 71 n = read(); 72 m = read(); 73 s = read(); 74 rep(i,1,m) { 75 int x = read(); 76 int y = read(); 77 int w = read(); 78 add(x,y,w); 79 } 80 dijkstra(); 81 rep(i,1,n) printf("%d ",dis[i]); 82 puts(""); 83 return 0; 84 }
> 别忘了 总有人在等着你

浙公网安备 33010602011771号