|
1 |
| -typedef pair<int,int> PII; //{dist, nodeIdx} |
| 1 | +typedef pair<int,int> PII; |
2 | 2 |
|
3 | 3 | class Solution {
|
4 |
| - |
| 4 | + int dist[3000]; |
| 5 | + int resolved[3000]; |
5 | 6 | public:
|
6 | 7 | int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n)
|
7 | 8 | {
|
8 |
| - vector<PII> adj[3000]; |
9 |
| - for (auto e:edges) |
| 9 | + vector<PII> adj[3000]; // {nextNode, weight} |
| 10 | + for (auto e: edges) |
10 | 11 | {
|
11 | 12 | adj[e[0]].push_back({e[1], e[2]+1});
|
12 | 13 | adj[e[1]].push_back({e[0], e[2]+1});
|
13 | 14 | }
|
14 | 15 |
|
15 |
| - priority_queue<PII, vector<PII>, greater<>>pq; |
16 |
| - pq.push({0, 0}); |
17 |
| - |
18 |
| - vector<int>dist(3000, INT_MAX/2); |
19 |
| - vector<int>resolved(3000); |
| 16 | + priority_queue<PII, vector<PII>, greater<>>pq; // {dist, nodeIdx} |
| 17 | + pq.push({0,0}); |
20 | 18 |
|
21 | 19 | while (!pq.empty())
|
22 | 20 | {
|
23 | 21 | auto [d, cur] = pq.top();
|
24 | 22 | pq.pop();
|
25 |
| - |
26 |
| - if (resolved[cur]==1) |
27 |
| - continue; |
| 23 | + if (resolved[cur]) continue; |
28 | 24 | resolved[cur] = 1;
|
29 | 25 | dist[cur] = d;
|
30 |
| - |
31 |
| - for (auto [next, len]: adj[cur]) |
| 26 | + |
| 27 | + for (auto [next, weight] : adj[cur]) |
32 | 28 | {
|
33 |
| - if (resolved[next]==1) continue; |
34 |
| - if (maxMoves >= d+len) |
35 |
| - pq.push({d+len, next}); |
36 |
| - } |
| 29 | + if (resolved[next]) continue; |
| 30 | + if (d+weight <= maxMoves) |
| 31 | + pq.push({d+weight, next}); |
| 32 | + } |
37 | 33 | }
|
38 | 34 |
|
39 | 35 | int count = 0;
|
40 | 36 | for (auto e: edges)
|
41 | 37 | {
|
42 |
| - int a = e[0], b = e[1], cnt = e[2]; |
| 38 | + int a = e[0], b = e[1]; |
43 | 39 | int sum = 0;
|
44 |
| - if (resolved[a]) sum += maxMoves-dist[a]; |
45 |
| - if (resolved[b]) sum += maxMoves-dist[b]; |
46 |
| - count += min(sum, cnt); |
| 40 | + if (resolved[a]) sum += maxMoves - dist[a]; |
| 41 | + if (resolved[b]) sum += maxMoves - dist[b]; |
| 42 | + count += min(sum, e[2]); |
47 | 43 | }
|
48 | 44 |
|
49 | 45 | for (int i=0; i<n; i++)
|
50 | 46 | if (resolved[i])
|
51 |
| - count += 1; |
| 47 | + count++; |
52 | 48 |
|
53 | 49 | return count;
|
| 50 | + |
54 | 51 | }
|
55 | 52 | };
|
0 commit comments