Cheapest Routes P40802


pdf   zip


We have collected abundant information about the local roads and accommodations in a region that we will traverse. Our plan is to go from city A to city B and we would like to spend the least possible money. For each road connecting two cities u and v we know the cost ω(u,v)=ω(v,u) to travel along that road (tolls, fuel, meals during the journey, …). Every time we go from a city u to one of its neighbors v we must stop at v and spend there one night; we know the cost ω′(v) of stopping at each city v (the cost added by A and B to our route is 0, since they are our initial and final points). All costs, of vertices and of edges, are positive. Thus the cost of the route

P = [A, v1, …, vn, B]


  cost(P) = ω(A,v1) + ω(v1,v2) + … + ω(vn,B)  + ω′(v1)+…+ω′(vn).

Write a program in C++ which, given an undirected weighted graph with positive costs at the vertices and at the edges, and two vertices A and B, returns the cost of the cheapest route to go from A to B, or an indication that not such route exists.

Input All data in the input are positive integers. The input starts with two integers 2≤n≤10000 and m, 0≤m≤20n. After that, a sequence of positive integers ω′(0), …, ω′(n−1) of the weights ω′(u) of the n vertices of the graph. Then the input contains a sequence of the m edges in the graph as triplets of the form ⟨u,v,ω(u,v)⟩. Vertices u and v are integers in {0,…,n−1} and the weights ω(u,v) are positive integers. No weight, of edges or vertices, is larger than 100000.

You can assume that there are no two different edges connecting the same pair of vertices nor any edge connecting a vertex to itself. Finally, there is a sequence of pairs ⟨Ai, Bi⟩, with each Ai and Bi denoting vertices of the graph (0≤Ai,Bi<n).

Output For each pair ⟨Ai, Bi⟩ in the input sequence the program writes the cost δ of the cheapest route between Ai and Bi. with the format c(Ai,Bi) = δ. If no route exists between Ai and Bi the program writes c(Ai,Bi) = +oo. The ouput for each case is ended with a newline (endl).

Public test cases
  • Input

    6 8
    3 6 10 15 5 2
    0 1 2  1 2 7  2 3 2 
    0 2 1  1 3 4  2 4 8
    3 4 2  3 0 5
    0 4
    1 4
    2 4
    3 1 
    4 1
    2 5
    2 2


    c(0,4) = 19
    c(1,4) = 21
    c(2,4) = 8
    c(3,1) = 4
    c(4,1) = 21
    c(2,5) = +oo
    c(2,2) = 0
  • Information
    Prof. EDA
    Other languages
    Catalan Spanish
    Official solutions
    User solutions