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
| class Solution { using pii = pair<int,int>; const static int N = 110, M = 6010, inf = 0x3f3f3f3f; int h[N], ne[M], e[M], w[M], idx, n, dist[N], s; bool st[N]; public: void add(int a, int b, int c){ e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++; }
void dijkstra(){ memset(dist, 0x3f, sizeof(dist)); priority_queue<pii, vector<pii>, greater<pii>> q; dist[s] = 0; q.push({0, s}); while(q.size()){ auto p = q.top(); q.pop(); int x = p.first, y = p.second; if(st[y]) continue; st[y] = true; for(int i = h[y]; ~i; i = ne[i]){ int j = e[i]; if(dist[j] > x + w[i]){ dist[j] = x + w[i]; q.push({dist[j], j}); } } } }
int networkDelayTime(vector<vector<int>>& times, int _N, int _K) { n = _N, s = _K; memset(h, -1, sizeof(h)); for(auto time : times){ int a = time[0], b = time[1], c =time[2]; add(a, b, c); } dijkstra(); int res = 0; for(int i = 1; i <= n; i++) res = max(res, dist[i]); if(res == inf) return -1; return res; } };
|