SystemYou are an expert competitive programmer. You solve problems by analyzing requirements, designing algorithms, and writing clean, efficient code. When solving problems, explain your reasoning step by step before providing...
You are an expert competitive programmer. You solve problems by analyzing requirements, designing algorithms, and writing clean, efficient code. When solving problems, explain your reasoning step by step before providing the final solution.
User
Problem Description: A city has N junctions connected by M roads. Each road has a primary and a secondary travel time, both of which are integers. The city council has two different traffic monitoring systems that use these travel times to guide drivers. Unfortunately, the two systems often disagree on which routes are optimal. Your task is to find the route from junction 1 to junction N that minimizes the total dissatisfaction from the two systems. Each system complains if a driver takes a road that it doesn't consider part of the optimal route from any junction to the destination.
Input Format:
The first line contains two integers N (2 ≤ N ≤ 10,000) and M (1 ≤ M ≤ 50,000).
The next M lines each contain four integers A, B, P, Q describing a road from junction A to junction B with primary travel time P and secondary travel time Q.
Output Format:
A single integer representing the minimum total dissatisfaction from both systems. Examples
while heap:
current_dist, u = heapq.heappop(heap)
if visited[u]:
continue
visited[u] = True
for (v, w) in graph[u]:
if dist[v] > current_dist + w:
dist[v] = current_dist + w
heapq.heappush(heap, (dist[v], v))
return dist
def main(): import sys input = sys.stdin.read().split() idx = 0 N = int(input[idx]) idx +=1 M = int(input[idx]) idx +=1
markdown
edges = []
for _ inrange(M):
A = int(input[idx])
idx +=1
B = int(input[idx])
idx +=1
P = int(input[idx])
idx +=1
Q = int(input[idx])
idx +=1
edges.append( (A, B, P, Q) )
# Build reversed graphs for P and Q
reversed_p_graph = [[] for _ inrange(N+1)]
for A, B, P, Q in edges:
reversed_p_graph[B].append( (A, P) )
reversed_q_graph = [[] for _ inrange(N+1)]
for A, B, P, Q in edges:
reversed_q_graph[B].append( (A, Q) )
# Compute dist_P and dist_Q
dist_P = dijkstra(reversed_p_graph, N, N)
dist_Q = dijkstra(reversed_q_graph, N, N)
# Build new_graph
new_graph = [[] for _ inrange(N+1)]
for A, B, P, Q in edges:
# Check if in R1if dist_P[B] == float('inf'):
in_r1 = Falseelse:
in_r1 = (dist_P[A] == dist_P[B] + P)
# Check if in R2if dist_Q[B] == float('inf'):
in_r2 = Falseelse:
in_r2 = (dist_Q[A] == dist_Q[B] + Q)
cost = 0ifnot in_r1:
cost += 1ifnot in_r2:
cost += 1
new_graph[A].append( (B, cost) )
# Find the shortest path in new_graph from 1 to N
min_dist = dijkstra(new_graph, 1, N)
if min_dist[N] == float('inf'):
print(-1)
else:
print(min_dist[N])