E - Come Back Quickly Editorial /

Time Limit: 3 sec / Memory Limit: 1024 MB

配点 : 500

問題文

AtCoder 国には、町 1 から町 N までの N 個の町と、道路 1 から道路 M までの M 本の道路があります。
道路 i は町 A_i から町 B_i への一方通行で、通るのに C_i 分かかります。A_i = B_i かもしれませんし、同じ町の組を結ぶ道路が複数あるかもしれません。
高橋君はこの国で散歩をしようと考えました。ある町から出発し、1 本以上の道路を通り、出発した町に帰ってくるような経路を正しい散歩経路と呼ぶことにします。
各町について、その町から出発する正しい散歩経路が存在するかを判定してください。また、存在するなら、そのような経路を通るのにかかる時間の最小値を求めてください。

制約

  • 1 \le N \le 2000
  • 1 \le M \le 2000
  • 1 \le A_i \le N
  • 1 \le B_i \le N
  • 1 \le C_i \le 10^5
  • 入力は全て整数

入力

入力は以下の形式で標準入力から与えられる。

N M
A_1 B_1 C_1
A_2 B_2 C_2
A_3 B_3 C_3
\hspace{25pt} \vdots
A_M B_M C_M

出力

N 行に渡って出力せよ。 i(1 \le i \le N) 行目には以下を出力せよ。

  • i から出発する正しい散歩経路が存在するなら、そのような経路を通るのにかかる時間の最小値
  • 存在しないなら -1

入力例 1

4 4
1 2 5
2 3 10
3 1 15
4 3 20

出力例 1

30
30
30
-1

道路 1, 2, 3 によって、町 1, 2, 3 は一周に 30 分かかる一つの輪のように繋がっています。
4 から町 1, 2, 3 に行くことはできますが、町 4 に帰ってくることはできません。


入力例 2

4 6
1 2 5
1 3 10
2 4 5
3 4 10
4 1 10
1 1 10

出力例 2

10
20
30
20

A_i = B_i であるような道路が存在するかもしれません。
この場合、町 1 からは、道路 6 だけを使って 10 分で町 1 に帰ってくることができます。


入力例 3

4 7
1 2 10
2 3 30
1 4 15
3 4 25
3 4 20
4 3 20
4 3 30

出力例 3

-1
-1
40
40

同じ町の組を結ぶ道路が複数あるかもしれないことに注意してください。

Score : 500 points

Problem Statement

In the Republic of AtCoder, there are N towns numbered 1 through N and M roads numbered 1 through M.
Road i is a one-way road from Town A_i to Town B_i, and it takes C_i minutes to go through. It is possible that A_i = B_i, 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

  • 1 \le N \le 2000
  • 1 \le M \le 2000
  • 1 \le A_i \le N
  • 1 \le B_i \le N
  • 1 \le C_i \le 10^5
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1 C_1
A_2 B_2 C_2
A_3 B_3 C_3
\hspace{25pt} \vdots
A_M B_M C_M

Output

Print N lines. The i-th line (1 \le i \le N) should contain the following:

  • if there is a valid walk that starts at Town i, 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 1, 2, 3, Towns 1, 2, 3 forms a ring that takes 30 minutes to go around.
From Town 4, we can go to Towns 1, 2, 3, but then we cannot return to Town 4.


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 A_i = B_i.
Here, we can use just Road 6 to depart from Town 1 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.