#abc191e. [abc191_e]Come Back Quickly
[abc191_e]Come Back Quickly
Problem Statement
In the Republic of AtCoder, there are towns numbered through and roads numbered through .
Road is a one-way road from Town to Town , and it takes minutes to go through. It is possible that , and there may be multiple roads connecting the same pair of towns.
Takahashi is thinking about taking a walk in the country. We will call a walk valid when it goes through one or more roads and returns to the town it starts at.
For each town, determine whether there is a valid walk that starts at that town. Additionally, if the answer is yes, find the minimum time such a walk requires.
Constraints
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
Print lines. The -th line should contain the following:
- if there is a valid walk that starts at Town , the minimum time required by such a walk;
- otherwise,
-1
.
Sample Input 1
4 4
1 2 5
2 3 10
3 1 15
4 3 20
Sample Output 1
30
30
30
-1
By Roads , Towns forms a ring that takes minutes to go around.
From Town , we can go to Towns , but then we cannot return to Town .
Sample Input 2
4 6
1 2 5
1 3 10
2 4 5
3 4 10
4 1 10
1 1 10
Sample Output 2
10
20
30
20
There may be a road such that .
Here, we can use just Road to depart from Town and return to that town.
Sample Input 3
4 7
1 2 10
2 3 30
1 4 15
3 4 25
3 4 20
4 3 20
4 3 30
Sample Output 3
-1
-1
40
40
Note that there may be multiple roads connecting the same pair of towns.