Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.82 KB | None | 0 0
  1. import java.io.File;
  2. import java.util.Scanner;
  3.  
  4. public class Quiz2{
  5. class Edge {
  6. int src, dest, weight;
  7. Edge()
  8. {
  9. src = dest = weight = 0;
  10. }
  11. };
  12.  
  13. int V, E;
  14. Edge edge[];
  15.  
  16.  
  17. public Quiz2(int v, int e)
  18. {
  19. V = v;
  20. E = e;
  21. edge = new Edge[e];
  22. for (int i = 0; i < e; ++i)
  23. edge[i] = new Edge();
  24. }
  25.  
  26. void Quiz2(Quiz2 graph, int src)
  27. {
  28. int V = graph.V, E = graph.E;
  29. int dist[] = new int[V+1];
  30.  
  31. // Step 1: Initialize distances from src to all other
  32. // vertices as INFINITE
  33. for (int i = 0; i < V; ++i)
  34. dist[i] = Integer.MAX_VALUE;
  35. dist[src] = 0;
  36.  
  37. // Step 2: Relax all edges |V| - 1 times. A simple
  38. // shortest path from src to any other vertex can
  39. // have at-most |V| - 1 edges
  40. for (int i = 1; i < V; ++i) {
  41. for (int j = 0; j < E; ++j) {
  42. int u = graph.edge[j].src;
  43. int v = graph.edge[j].dest;
  44. int w = graph.edge[j].weight;
  45. if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v])
  46. dist[v] = dist[u] + w;
  47. }
  48. }
  49.  
  50. // Step 3: check for negative-weight cycles. The above
  51. // step guarantees shortest distances if graph doesn't
  52. // contain negative weight cycle. If we get a shorter
  53. // path, then there is a cycle.
  54. for (int j = 0; j < E; ++j) {
  55. int u = graph.edge[j].src;
  56. int v = graph.edge[j].dest;
  57. int w = graph.edge[j].weight;
  58. if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
  59. System.out.println("Graph contains negative weight cycle");
  60. return;
  61. }
  62. }
  63. print(dist, V);
  64. }
  65.  
  66.  
  67. void print(int dist[], int V)
  68. {
  69. System.out.println("Vertex Distance from Source");
  70. for (int i = 0; i < V; ++i)
  71. System.out.println(i + "\t\t" + dist[i]);
  72. }
  73.  
  74. public static void main(String args[]) throws Exception{
  75.  
  76. int source;
  77. Scanner sc;
  78. try {
  79.  
  80. File f = new File("C:\\Users\\18101590\\Desktop\\quize 2\\quiz.txt");
  81.  
  82. sc = new Scanner(f);
  83.  
  84. int n = sc.nextInt();
  85. int e = sc.nextInt();
  86.  
  87.  
  88.  
  89. Quiz2 t = new Quiz2(n,e);
  90. for (int i = 0; i < e; i++) {
  91. int u = sc.nextInt();
  92. int v = sc.nextInt();
  93. int w = sc.nextInt();
  94. t.edge[i].src=u;
  95. t.edge[i].dest=v;
  96. t.edge[i].weight=w;
  97. }
  98. int s=sc.nextInt();
  99. t.Quiz2(t,s);
  100. }catch (Exception e){
  101. e.printStackTrace();
  102. }
  103. }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement