算法导论 24-2

24-4 嵌套框

也就是求有向图无环图的最长路径

 

We consider d-dimensional boxes.
a. The nesting relation is clearly transitive.
b. We can determine if a box nests within another by sorting the dimensions of each box and
comparing them sequentially.
c. To nd the longest nest sequence we determine the nesting relations on all boxes by sorting
each in O(d lg d) time and comparing then pairwise in O(d) time for each of the O(n2) pairs. This
produces a partial relation (by denition of nesting) and thus a directed acyclic graph in which we
nd the longest path using O(n2+n) time. The total running time is thus O(d lg d+dn2+n2+n) =
O(d(n2 + lg d)).

 在bellman-ford 一章  就用bellman-Ford算法求解把

 就是添加一个原点s 到其他点的权值为0 ,把各边的权值取反,求出最短路 再 取反就得到了最长路.

 当然 貌似也可以用dfs()求解.

 

 

以下copy的:

我们知道这个算法是求单源最短路径的,并且允许边的权值为负, 如果存在负环,那么该算法还可以检测到。
现在我们的问题是给出一个有向图,如果其中有环,则返回-1,否则返回其中最长的有向路的长度。
这个也是可以用bellman-ford来做的。
我们把所有的边的权取反,初始化dis数组的所有值都为0,注意这步的意思,所有的初始化为0,表示我们假想有一个源点s,它到其他所有点有边,别且权值为0,这样求该假想点到其他所有点的最短路(注意路的长度都为负值了)。
bellman-ford算法正好可以干这个事情,而且如果存在负环,它还能检测出来。
这样,我们最后只需找到dis中最小值,然后取反就是所求。
至于证明,可以用反证法。假设原图中存在更长的无欢路,那么反图中的bellman-ford一定可以找到。

int[] d = new int[n];
    for (int i = 0; i < n; i++)
        d[i] = 0;
    for (int step = 0; step < n; step++)
    {
        for (int i = 0; i < n; i++)
        {
        for (int j = 0; j < n; j++)
        {
            if (map[i][j] !=INF&& d[j] > d[i] - map[i][j])
            {
            d[j] = d[i] - map[i][j];
            if (step == n-1)
                return -1;
            }
        }
        }
    }

另外还可以想一下原始的bellman-ford算法,如果检测的负环,那么这个负环即可以从源点可达的,也可以是从源点不可达的。
下面这段是从算法导论上copy的
BELLMAN-FORD(Gws
    1 INITIALIZE-SINGLE-SOURCE(Gs
    for i  1 to |V[G]| - 1 
        do for each edge (uv E[G]
        do RELAX(uvw
    for each edge (uv E[G
    do if d[v> d[u] + w(uv
        then return FALSE 
    return TRUE 
我想假设存在负环,但是不可以源点可达,那么不应该返回false,怎么办呢?

我的想法是:首先INF+const==INF
也就是说第6行中的code,应该写成: do if  d[v]!=INF&&d[v]>d[u]+w(u,v)  

is not INF,表示明显不是INF

http://hi.baidu.com/rangemq/blog/item/0e96cad3977cdcdea9ec9ac6.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值