我想将具有 N 个加权顶点和 N-1 个边的图划分为三个部分,以使每个部分中所有顶点的权重总和的最大值最小化。这是我试图解决的实际问题,http://www.iarcs.org.in/inoi/contests/jan2006/Advanced-1.php
我考虑了以下方法
/*Edges are stored in an array E, and also in an adjacency matrix for depth first search.
Every edge in E has two attributes a and b which are the nodes of the edge*/
min-max = infinity
for i -> 0 to length(E):
for j -> i+1 to length(E):
/*Call depth first search on the nodes of both the edges E[i] and E[j]
the depth first search returns the sum of weights of the vertices it visits,
we keep track of the maximum weight returned by dfs*/
Adjacency-matrix[E[i].a][E[i].b] = 0;
Adjacency-matrix[E[j].a][E[j].b] = 0;
max = 0
temp = dfs(E[i].a)
if temp > max then max = temp
temp = dfs(E[i].b)
if temp > max then max = temp
temp = dfs(E[i].a)
if temp > max then max = temp
temp = dfs(E[i].a)
if temp > max then max = temp
if max < min-max
min-max = max
Adjacency-matrix[E[i].a][E[i].b] = 1;
Adjacency-matrix[E[j].a][E[j].b] = 1;
/*The depth first search is called four times but it will terminate one time
if we keep track of the visited vertices because there are only three components*/
/*After the outer loop terminates what we have in min-max will be the answer*/
上述算法需要 O(n^3) 时间,因为边的数量将是 n-1,外循环将运行 (n-1)!需要 O(n^2) 的时间,dfs 将只访问每个顶点一次,因此是 O(n) 时间。
但问题是 n 可以 <= 3000 并且 O(n^3) 时间不适合这个问题。是否有任何其他方法可以比 n^3 更快地计算解决链接中的问题?
编辑:
我在 c 中实现了@BorisStrandjev 的算法,它给了我对问题中测试输入的正确答案,但对于所有其他测试输入,它给出了错误答案,这是我在 ideone http://ideone.com中的代码的链接/67GSa2,这里的输出应该是 390 但程序会打印 395。我试图找出我的代码是否有任何错误,但我没有看到任何错误。任何人都可以在这里帮助我,我的代码给出的答案非常接近正确答案,那么算法还有什么更多的吗?
编辑2:
在下图中-@BorisStrandjev,您的算法将在其中一次迭代中选择 i 作为 1, j 作为 2,但是第三部分 (3,4) 无效。
编辑 3
我终于在我的代码中遇到了错误,而不是 V[i] 存储 i 的总和及其所有后代,而是存储 V[i] 及其祖先,否则它将正确解决上述示例,感谢大家的帮助.