Shortest Path or Negative Cycle
InterviewTime limit4sMemory limit128 MB
Given a directed weighted graph and a source vertex s, output a negative cycle if one exists, otherwise the shortest distance from s to every vertex.
- Level
Medium4 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
A graph with vertices and edges is given. The vertices are numbered . A vertex is also given. For every vertex , there is a path from to .
Edge goes from vertex to vertex and has weight . may be negative.
If the graph has a negative cycle, return any one of them.
If the graph has no negative cycle, print the length of the shortest path from to for every vertex .
Input
The first line contains the integers , , and .
Each of the next lines contains , , and .
Output
If the graph has a negative cycle:
- The first line prints CYCLE.
- The second line prints , the number of edges in the negative cycle. .
- The third line prints integers . and are the start and end vertices of the -th edge of the cycle. , and the cycle includes each edge at most once.
If the graph has no negative cycle:
- The first line prints PATH.
- The second line prints integers , where is the sum of weights on the shortest path from to .
Constraints
- ()
- For every vertex , there is a path from to .