Shortest Path Again?
Shortest path algorithms
Graphs
Algorithms
87.0% success
1,256 attempts
5s time
256MB memory
1024KB max code

There are N cities and Demon is in city 1. Now, there are M pair of roads between some cities and each of the roads have cost to travel by it. The cost to travel from city c1 to ck is 1*w1 + 2*w2 + 3*w3+......+(k-1)*wk-1 where wi is the cost to travel from city pi to city pi+1. Demon is lazy and so he wants you to find the minimum cost to travel from city 1 to every other city from 1 to N. If there exists no path to travel from city 1 to city i, print -1.

Note: There can be self-loop roads or multiple edge roads. All the roads are bidirectional.

Input:
The first line contains two space-separated integers n and m - the number of nodes and edges respectively. The next m lines contain three space-separated integers x, y, and w - representing an edge between x and y with cost w

Constraints:
1<=n<=3000
0<=m<=10000
1<=x,y<=n
1<=w<=1e9

Output:
Output n lines. In the ith line, output the minimum distance from city 1 to the ith city. If there exists no such path, output -1.

Examples
Input
6 5
2 4 3
2 3 4
2 1 2
2 5 6
1 5 2
Output
0
2
10
8
2
-1
Explanation

Explanation:
The shortest path from 1 to 3 is (1 -> 2 ->3) with total weight 1*2 + 2*4 = 10.
The shortest path from 1 to 5 is (1 -> 5) with total weight 1*2 = 2.
There doesn't exist any path from 1 to 6, so print -1.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading Editor...