无法为bellman-ford算法生成正确的图形

时间:2016-05-12 14:42:44

标签: java algorithm graph bellman-ford

我有贝尔曼 - 福特算法的实现。 输入程序提供了一个边缘列表。 没有优化,它看起来像这样:

int i, j;
        for (i = 0; i < number_of_vertices; i++) {
            distances[i] = MAX;
        }
        distances[source] = 0;
        for (i = 1; i < number_of_vertices - 1; ++i) {

            for (j = 0; j < e; ++j) { //here i am calculating the shortest path
                if (distances[edges.get(j).source] + edges.get(j).weight < distances[edges.get(j).destination]) {
                    distances[edges.get(j).destination] = distances[edges.get(j).source] + edges.get(j).weight;
                }
            }
        }

它具有O(V * E)的复杂性 但通过优化,他的工作速度非常快。它看起来像

while (true) {

            boolean any = false;
            for (j = 0; j < e; ++j) { //here i am calculating the shortest path
                if (distances[edges.get(j).source] + edges.get(j).weight < distances[edges.get(j).destination]) {
                    distances[edges.get(j).destination] = distances[edges.get(j).source] + edges.get(j).weight;
                    any = true;
                }
            }
            if (!any) break;
        }

实际上,如果外环中的顶点数(例如一万个)只有10-12次迭代而不是10万次,那么算法就完成了它的工作。

这是我的生成代码:

//q - vertices

for (int q = 100; q <= 20000; q += 100) {
          List<Edge> edges = new ArrayList();
                for (int i = 0; i < q; i++) {
                    for (int j = 0; j < q; j++) {
                        if (i == j) {
                            continue;
                        }

                        double random = Math.random();
                        if (random < 0.005) {
                            int x = ThreadLocalRandom.current().nextInt(1, 100000);
                           edges.add(new Edge(i, j, x));
                            edges++;
                        }
                    }

                }
              //write edges to file edges
            }

但是我需要生成一个图表,完成他的工作不会那么快。那可以在发电机中改变吗?

1 个答案:

答案 0 :(得分:1)

像你所说的Bellman Ford算法的复杂性是O(| E | * | V |)。在你的生成器中,添加边缘的概率可以忽略不计(0.005),这就是为什么我认为代码运行得很快。

增加概率,应该有更多的边缘,因此贝尔曼福特需要更长的时间。

相关问题