-
Notifications
You must be signed in to change notification settings - Fork 25
/
no_of_ways.cpp
66 lines (52 loc) · 1.79 KB
/
no_of_ways.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;
const int MOD = 1e9 + 7;
int countWaysToDestination(int n, vector<vector<int>>& roads)
{
vector<vector<pair<int, int>> > adj(n);
for (auto road : roads)
{
int u = road[0], v = road[1], t = road[2];
adj[u].push_back({v, t});
adj[v].push_back({u, t});
}
vector<long long> shortestTime(n, LLONG_MAX);
vector<long long> ways(n, 0);
priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
pq.push({0, 0});
shortestTime[0] = 0;
ways[0] = 1;
while (!pq.empty())
{
auto [time, current] = pq.top();
pq.pop();
if (time > shortestTime[current])
{
continue;
}
for (auto [neighbor, neighborTime] : adj[current])
{
if (shortestTime[neighbor] > shortestTime[current] + neighborTime)
{
shortestTime[neighbor] = shortestTime[current] + neighborTime;
pq.push({shortestTime[neighbor], neighbor});
ways[neighbor] = ways[current];
} else if (shortestTime[neighbor] == shortestTime[current] + neighborTime)
{
ways[neighbor] = (ways[neighbor] + ways[current]) % MOD;
}
}
}
return ways[n - 1];
}
int main()
{
int n = 7;
vector<vector<int>> 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}};
int ways = countWaysToDestination(n, roads);
cout << "Number of ways to reach the destination in the shortest time: " << ways << endl;
return 0;
}