D - 最安経路 / Cheapest Route Editorial by admin
Gemini 3.1 Pro (Thinking)Overview
This is a problem of finding the shortest path (minimum cost) from city \(1\) to any city that has an airport, in a graph where cities are vertices and roads are edges.
Analysis
The toll for traveling between cities is determined by the product of the populations of the origin city and the destination city. This can be thought of as each road (edge) having a fixed cost of \(M_a \times M_b\) assigned in advance.
Additionally, since the population \(M_i\) of each city is at least \(1\), the toll (edge cost) is always a positive value. For a single-source shortest path problem on a graph with non-negative edge costs like this, Dijkstra’s Algorithm can be used to solve it efficiently.
If we use a simple breadth-first search (BFS) that does not consider edge costs, we cannot obtain the correct minimum cost. Also, using the Bellman-Ford algorithm would result in a time complexity of \(O(N \times K)\), which would exceed the time limit (TLE) under the given constraints (\(N, K \le 2 \times 10^5\)). Therefore, using Dijkstra’s algorithm with a priority queue (heap) is the optimal approach.
Algorithm
- Graph Construction: For each road connecting cities \(U_k\) and \(V_k\), add an undirected edge to the graph with cost \(M_{U_k} \times M_{V_k}\). (Example: If city \(2\) has a population of \(3\) and city \(3\) has a population of \(5\), and there is a road connecting them, then the cost of this edge is \(3 \times 5 = 15\).)
- Shortest Distance Calculation (Dijkstra’s Algorithm):
- Initialize the distance of city \(1\) (the starting point) to \(0\), and the distance of all other cities to infinity (\(\infty\)).
- Add
(distance 0, city 1)to the priority queue. - Extract the city with the currently shortest distance from the queue, and calculate the distance when moving to adjacent cities connected to it. If this distance is shorter than the currently recorded distance, update the value and add the new distance-city pair to the queue.
- Repeat this until the queue is empty.
- Deriving the Answer: For cities with airports \(E_1, E_2, \dots, E_P\), check the computed shortest distances from city \(1\), and output the smallest value among them as the answer.
Complexity
- Time complexity: \(O((N + K) \log N)\) Graph construction takes \(O(N + K)\), and the shortest path computation using Dijkstra’s algorithm takes \(O((N + K) \log N)\). This comfortably fits within the time limit even for the maximum constraint values.
- Space complexity: \(O(N + K)\) Storing the graph’s adjacency list requires \(O(N + K)\), and the distance array and priority queue use \(O(N)\) memory.
Implementation Notes
Fast I/O: In Python, since the input data can be very large, reading all input at once using
sys.stdin.read().split()can significantly reduce execution time.Infinity Initial Value: The initial value for distances (infinity) must be set to a sufficiently large value (e.g., \(10^{18}\)) that exceeds the maximum possible answer.
Skipping Outdated Information: When extracting an element from the priority queue, skipping outdated information where the shortest distance has already been updated (e.g.,
if d > dist[u]: continue) eliminates unnecessary exploration.Source Code
import sys
import heapq
def main():
input_data = sys.stdin.read().split()
if not input_data:
return
N = int(input_data[0])
K = int(input_data[1])
P = int(input_data[2])
M = [0] * (N + 1)
for i in range(1, N + 1):
M[i] = int(input_data[2 + i])
adj = [[] for _ in range(N + 1)]
idx = 3 + N
for _ in range(K):
u = int(input_data[idx])
v = int(input_data[idx + 1])
idx += 2
cost = M[u] * M[v]
adj[u].append((v, cost))
adj[v].append((u, cost))
INF = 10**18
dist = [INF] * (N + 1)
dist[1] = 0
pq = [(0, 1)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, cost in adj[u]:
nd = d + cost
if dist[v] > nd:
dist[v] = nd
heapq.heappush(pq, (nd, v))
ans = min(dist[int(input_data[i])] for i in range(idx, idx + P))
print(ans)
if __name__ == '__main__':
main()
This editorial was generated by gemini-3.1-pro-thinking.
posted:
last update: