You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.
Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo109 + 7.
Example 1:
Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
Output: 4
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
Example 2:
Input: n = 2, roads = [[1,0,10]]
Output: 1
Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
Solution: (Dijkstra)
classSolution{public: int dijkstra(vector<pair<long long int, long long int>> v[], vector<bool> &vs, vector<long long int> &key, vector<int> &ways, int src, int n)
{int mod =1000000000+7; priority_queue<pair<long long int, long long int>, vector<pair<long long int, long long int>>, greater<pair<long long int, long long int>>> pq;
pq.push({0, src});key[src] =0;ways[src] =1;while (!pq.empty()) {longlongint node =pq.top().second;longlongint weight =pq.top().first;pq.pop();if (vs[node]) {continue; }vs[node] =1;for (int i =0; i <v[node].size(); i++) {longlongint in =v[node][i].first;longlongint wt =v[node][i].second;if (wt + weight <key[in]) {key[in] = wt + weight;pq.push({wt + weight, in});ways[in] =ways[node]; }elseif (wt + weight ==key[in]) {ways[in] = (ways[in] +ways[node]) % mod; } } }returnways[n -1]; }intcountPaths(int n,vector<vector<int>> &roads) { vector<pair<longlongint,longlongint>>v[n];for (int i =0; i <roads.size(); i++) {v[roads[i][0]].push_back({roads[i][1],roads[i][2]});v[roads[i][1]].push_back({roads[i][0],roads[i][2]}); } vector<bool>vs(n,false); vector<longlongint>key(n, LONG_MAX); vector<int>ways(n,0);returndijkstra(v, vs, key, ways,0, n); }};