Bellmen Ford

題目連接java


根據Bellmen Ford算法判斷是否存在負環算法

import java.util.Scanner;

/**
 * O(n * m)
 */
public class Main {

    static class Edge {
        int from;
        int to;
        int weight;

        public Edge(int from, int to, int weight) {
            this.from = from;
            this.to = to;
            this.weight = weight;
        }
    }

    private static final int INF = Integer.MAX_VALUE;

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        while (in.hasNext()) {

            int F = in.nextInt();

            while (F -- > 0) {

                int n = in.nextInt();
                int m = in.nextInt();
                int t = in.nextInt();

                int[] dist = new int[n + 1];

                for (int i = 1; i <= n; ++ i) {
                    dist[i] = INF;
                }
                dist[1] = 0;

                Edge[] edges = new Edge[t + m * 2];
                int edgeIndex = 0;

                while (m -- > 0) {
                    int a = in.nextInt();
                    int b = in.nextInt();
                    int c = in.nextInt();
                    edges[edgeIndex ++] = new Edge(a, b, c);
                    edges[edgeIndex ++] = new Edge(b, a, c);
                }

                while (t -- > 0) {
                    int a = in.nextInt();
                    int b = in.nextInt();
                    int c = in.nextInt();
                    edges[edgeIndex ++] = new Edge(a, b, -c);
                }

                /**
                 * n - 1 輪鬆弛
                 */
                for (int i = 1; i < n; ++ i) {

                    boolean flag = false;

                    for (int j = 0; j < edges.length; ++ j) {

                        Edge edge = edges[j];

                        if (dist[edge.from] != INF && dist[edge.to] > dist[edge.from] + edge.weight) {
                            dist[edge.to] = dist[edge.from] + edge.weight;
                            flag = true;
                        }
                    }

                    // 本輪未鬆弛,結束
                    if (! flag) {
                        break;
                    }
                }

                boolean exist = false;

                // n - 1 輪鬆弛後還能鬆弛,有負環
                for (int j = 0; j < edges.length; ++ j) {

                    Edge edge = edges[j];

                    if (dist[edge.from] != INF && dist[edge.to] > dist[edge.from] + edge.weight) {
                        exist = true;
                    }
                }

                if (exist) {
                    System.out.println("YES");
                } else {
                    System.out.println("NO");
                }
            }

        }
    }
}
相關文章
相關標籤/搜索