import java.util.*;

class BellmanFord {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter number of vertices: ");
        int v = sc.nextInt();

        System.out.print("Enter number of edges: ");
        int e = sc.nextInt();

        int[][] edges = new int[e][3];

        System.out.println("Enter edges (source destination weight):");
        for (int i = 0; i < e; i++) {
            edges[i][0] = sc.nextInt();
            edges[i][1] = sc.nextInt();
            edges[i][2] = sc.nextInt();
        }

        System.out.print("Enter source vertex: ");
        int src = sc.nextInt();

        int[] dist = new int[v];
        Arrays.fill(dist, 99999);
        dist[src] = 0;

        for (int i = 1; i < v; i++) {
            for (int j = 0; j < e; j++) {
                int u = edges[j][0];
                int w = edges[j][1];
                int wt = edges[j][2];

                if (dist[u] != 99999 &&
                    dist[u] + wt < dist[w]) {
                    dist[w] = dist[u] + wt;
                }
            }
        }

        for (int j = 0; j < e; j++) {
            int u = edges[j][0];
            int w = edges[j][1];
            int wt = edges[j][2];

            if (dist[u] != 99999 &&
                dist[u] + wt < dist[w]) {
                System.out.println("Negative cycle exists!");
                return;
            }
        }

        System.out.println("Shortest distances:");

        for (int i = 0; i < v; i++) {
            System.out.println("Vertex " + i + " : " + dist[i]);
        }
    }
}