Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. public void outputData() throws FileNotFoundException {
  2.         PrintWriter out = new PrintWriter("negcycle.out");
  3.         int start = findNegativeCycle();
  4.         if (start == -1) {
  5.             out.print("NO");
  6.         } else {
  7.             int finish = start;
  8.             for (int i = 0; i < countVertices; i++) {
  9.                 finish = parent[finish];
  10.             }
  11.             ArrayList<Integer> path = new ArrayList<>();
  12.             for (int j = finish; ; j = parent[j]) {
  13.                 path.add(j);
  14.                 if (j == finish && path.size() > 1) break;
  15.             }
  16.             out.println("YES");
  17.             out.println(path.size());
  18.             for (int i = path.size() - 1; i >= 0; i--) {
  19.                 out.print((path.get(i) + 1) + " ");
  20.             }
  21.         }
  22.         out.close();
  23.     }
  24.  
  25.     private int findNegativeCycle() {
  26.         dist = new int[countVertices];
  27.         parent = new int[countVertices];
  28.         Arrays.fill(dist, 1000_000_000);
  29.         Arrays.fill(parent, -1);
  30.         dist[0] = 0;
  31.         int start = -1;
  32.         for (int k = 0; k < countVertices; k++) {
  33.             start = -1;
  34.             for (int i = 0; i < countVertices; i++) {
  35.                 for (int j = 0; j < countVertices; j++) {
  36.                     if (dist[j] > dist[i] + matrix[i][j]) {
  37.                         parent[j] = i;
  38.                         dist[j] = dist[i] + matrix[i][j];
  39.                         start = j;
  40.                     }
  41.                 }
  42.             }
  43.         }
  44.         return start;
  45.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement