CP: How many cheapest routes?

A delivery network has n hubs and m one-way links, each with a cost. Find the cheapest cost from hub 1 to hub n, and the number of different routes that achieve that cost, modulo 10⁹ + 7.

What to build

Run Dijkstra from hub 1 and keep a second array ways. When a strictly cheaper path to v is found through u, set ways[v] = ways[u]. When an equally cheap path is found, add: ways[v] = (ways[v] + ways[u]) % MOD.

Requirements

  • Use Dijkstra with a priority queue
  • Count routes modulo 10⁹ + 7
  • Print -1 if hub n cannot be reached

Input

The first line has n and m. Each of the next m lines has a b w: a link from a to b with cost w.

Output

COST WAYS, or -1.

Constraints

2 ≤ n ≤ 2,000. 0 ≤ m ≤ 10,000. 1 ≤ w ≤ 10⁶.

Example

Input:

4 5
1 2 1
1 3 1
2 4 1
3 4 1
2 3 5

Output:

2 2

Why it works

Every cost is positive, so when Dijkstra finalises a vertex, all cheapest routes into it come from vertices already finalised and ways[u] is complete when u is popped. Adding ways[u] for each equal-cost relaxation counts every cheapest route exactly once.

Examples

Example 1 · Input
4 5
1 2 1
1 3 1
2 4 1
3 4 1
2 3 5
Expected output
2 2
Example 2 · Input
3 1
1 2 4
Expected output
-1

Hints

Hint 1

Start with ways[1] = 1 and dist[1] = 0.

Hint 2

If dist[u] + w < dist[v]: dist[v] = dist[u] + w; ways[v] = ways[u]; push. Else if equal: ways[v] += ways[u].

Hint 3

Skip stale queue entries first, so each vertex is expanded once at its final distance.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <queue>
#include <vector>
using namespace std;

int main() {
    const long long MOD = 1000000007;
    const long long INF = 4000000000000000000LL;
    int n, m;
    cin >> n >> m;
    vector<vector<pair<int, int> > > adj(n + 1);
    for (int i = 0; i < m; i++) {
        int a, b, w;
        cin >> a >> b >> w;
        adj[a].push_back(make_pair(b, w));
    }
    vector<long long> dist(n + 1, INF), ways(n + 1, 0);
    priority_queue<pair<long long, int> > pq;
    dist[1] = 0;
    ways[1] = 1;
    pq.push(make_pair(0LL, 1));
    while (!pq.empty()) {
        long long d = -pq.top().first;
        int u = pq.top().second;
        pq.pop();
        if (d > dist[u]) continue;
        for (size_t k = 0; k < adj[u].size(); k++) {
            int v = adj[u][k].first;
            long long w = adj[u][k].second;
            if (dist[u] + w < dist[v]) {
                dist[v] = dist[u] + w;
                ways[v] = ways[u];
                pq.push(make_pair(-dist[v], v));
            } else if (dist[u] + w == dist[v]) {
                ways[v] = (ways[v] + ways[u]) % MOD;
            }
        }
    }
    if (dist[n] == INF) cout << -1 << "\n";
    else cout << dist[n] << " " << ways[n] << "\n";
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Shortest paths: Dijkstra and Floyd →