PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BF0000002. Đường đi ngắn nhất với cạnh âm (Shortest Path with Negative Edges)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đường đi ngắn nhất với cạnh âm (Shortest Path with Negative Edges)

Shortest Path with Negative Edges

Source: AOJ

Version: Phuoc Hung OJ Extended

Problem Statement

Find shortest paths from source r, or print NEGATIVE CYCLE if a negative cycle is reachable from r.

You are given a directed weighted graph with vertices 0,1,…,n−10,1,\ldots,n-1, and a specified source vertex rr. Edge weights may be negative, and some vertices may be unreachable from rr.

If a negative-weight cycle can be reached from rr, path costs can be decreased without bound along its reachable region. In this case, print NEGATIVE CYCLE instead of distances. Otherwise, print the shortest path distance from rr to each vertex, using INF where no path exists. A negative cycle disconnected from the source does not trigger the special message.

Input

First line: n,m,rn,m,r. Next mm lines: u,v,wu,v,w, vertices from 0 through n−1n-1.

Output

Print NEGATIVE CYCLE if reachable, else nn lines containing distances or INF.

Subtasks

  • Subtask 1 (20 points): 1≤n≤201\le n\le20; 0≤m≤500\le m\le50; −10000≤w≤10000-10000\le w\le10000; no self-loops or duplicate ordered edges; source 0..n−1.
  • Subtask 2 (30 points): 1≤n≤1501\le n\le150; 0≤m≤5000\le m\le500; −10000≤w≤10000-10000\le w\le10000; no self-loops or duplicate ordered edges; source 0..n−1.
  • Subtask 3 (50 points): 1≤n≤10001\le n\le1000; 0≤m≤20000\le m\le2000; −10000≤w≤10000-10000\le w\le10000; no self-loops or duplicate ordered edges; source 0..n−1.

Examples

Input

4 6 0
0 1 2
0 2 3
1 2 -5
1 3 1
2 3 2
3 1 0

Output

NEGATIVE CYCLE

Explanation

Relaxation finds eligible paths, or a negative cycle in the required scope. The sample uses the exact output tokens specified by the problem.