java | 差分约束系统模版(Bellman-Ford)

该代码展示了如何使用Java实现差分约束条件下的Bellman-Ford算法,用于求解有向图中从超级源点0到其他节点的最短路径。算法在给定边的集合和起点0的基础上进行n-1次松弛操作,检查是否存在负权回路。
摘要由CSDN通过智能技术生成
  • x_j - x_i \leq w
  • 表示建立一条从i到j的一条权值为w的边,由于算法是对所有的边进行遍历,所以不需要用链式前向星。
  • 注意要加入一个超级源点0,它到其他所有节点都有一条权值为0的边。
  • 使用Bellman-Ford最短路算法,如果在n - 1次松弛后还能够继续更新,则可行解不存在。 
import java.io.*;
import java.util.Arrays;

public class 差分约束 {
    public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static StreamTokenizer t = new StreamTokenizer(br);
    public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    public static PrintWriter out = new PrintWriter(bw);
    public static int nextInt() throws Exception {
        t.nextToken();
        return (int) t.nval;
    }

    public static int n, m;
    public static class Edge {
        int u;
        int v;
        int w;
        public Edge(int u, int v, int w) {
            this.u = u;
            this.v = v;
            this.w = w;
        }
    }
    public static Edge[] edges;
    public static int[] head, dist;
    public static boolean Bellman_Ford() {
        for (int i = 0; i < n - 1; i += 1) {
            for (int j = 0; j < m; j += 1) {
                int u = edges[j].u, v = edges[j].v, w = edges[j].w;
                if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
                    dist[v] = dist[u] + w;
                }
            }
        }
        for (int i = 0; i < m; i += 1) {
            int u = edges[i].u, v = edges[i].v, w = edges[i].w;
            if (dist[u] != Integer.MAX_VALUE && dist[u] + w < dist[v]) {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) throws Exception {
        n = nextInt();
        m = nextInt();
        edges = new Edge[m + n];
        head = new int[n + 1];
        dist = new int[n + 1];
        Arrays.fill(head, -1);
        Arrays.fill(dist, Integer.MAX_VALUE);
        dist[0] = 0;
        for (int i = 0; i < m; i += 1) {
            int u = nextInt(), v = nextInt(), w = nextInt();
            edges[i] = new Edge(v, u, w);
        }
        for (int i = 1; i <= n; i += 1) {
            edges[m] = new Edge(0, i, 0);
            m += 1;
        }
        if (Bellman_Ford()) {
            for (int i = 1; i <= n; i += 1) {
                out.print(dist[i] + " ");
            }
        } else {
            out.print("NO");
        }
        out.flush();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值