为你写诗

c/c++
随笔 - 32, 文章 - 0, 评论 - 3, 引用 - 0
数据加载中……

最长递增子序列dp

原创  动态规划 (DP) 之 最长递增子序列(Longest Increase Subsequence)

原文:http://blog.csdn.net/hhygcy/archive/2009/03/02/3950158.aspx

既然已经说到了最长公共子序列,就把这个递增子序列也说了。同样的,这里subsequence表明了这样的子序列不要求是连续的。比如说有子序列{1, 9, 3, 8, 11, 4, 5, 6, 4, 19, 7, 1, 7 }这样一个字符串的的最长递增子序列就是{1,3,4,5,6,7}或者{1,3,4,5,6,19}。

其实这个问题和前面的最长公共子序列问题还是有一定的关联的。假设我们的初始的序列S1。那我们从小到大先排序一下。得到了S1'。这样我们再球S1和S1'的最长公共子序列就可以知道答案了:)是不是有点巧妙啊。这个过程还是比较直观的。但是这个不是这次要说的重点,这个问题有比较传统的做法的.

我们定义L(j)是一个优化的子结构,也就是最长递增子序列.那么L(j)和L(1..j-1)的关系可以描述成

L(j) = max {L(i), i<j && Ai<Aj  } + 1;  也就是说L(j)等于之前所有的L(i)中最大的的L(i)加一.这样的L(i)需要满足的条件就是Ai<Aj.这个推断还是比较容易理解的.就是选择j之前所有的满足小于当前数组的最大值.

很容易的我们写出了下面的代码:

  1. // Longest_Increase_subsequence.cpp : Defines the entry point for the console application.  
  2. //  
  3. #include "stdafx.h"  
  4. #include <vector>  
  5. #include <iostream>  
  6. #include "windows.h"  
  7. /** 
  8. * Description: Calulate the longest increase subsequence 
  9. *@param s1, source sequence 
  10. *@param s2, output, longest increase sequence 
  11. */  
  12. template<typename T> void longest_increase_subsequence(const std::vector<T>& s1, std::vector<T>& s2)  
  13. {  
  14.       
  15.     int n = s1.size(); if (n<1) return;  
  16.     int m = 0;  
  17.     int k = 0;  
  18.     std::vector<unsigned int> b(n+1, 1);  
  19.     std::vector<unsigned int> p(n+1, 0);  
  20.               
  21.     for (int i=1;i<=n;i++)     
  22.     {  
  23.         for (int j=1;j<i;j++)  
  24.         {  
  25.             if ( s1[i-1] > s1[j-1] && b[i] < b[j] +1 )  
  26.             {  
  27.                 b[i] = b[j] + 1;  
  28.                 p[i] = j;  
  29.             }     
  30.         }  
  31.     }     
  32.     for ( int i=1;i<=n;i++)  
  33.     {  
  34.         if (m<b[i])  
  35.         {     
  36.             m = b[i];  
  37.             k = i;  
  38.         }     
  39.     }     
  40.     s2.resize(m);  
  41.     while (k>0)  
  42.     {  
  43.         s2[m-1] = s1[k-1];  
  44.         m--;  
  45.         k = p[k];  
  46.     }  
  47. }  
  48. int _tmain(int argc, _TCHAR* argv[])  
  49. {  
  50.     int a[] = { 1, 9, 3, 8, 11, 4, 5, 6, 4, 19, 7, 1, 7 };  
  51.     std::vector<int> seq(a, a+sizeof(a)/sizeof(a[0]));  
  52.     std::vector<int> r;  
  53.     longest_increase_subsequence(seq, r);  
  54.     for (int i=0;i<r.size();i++)  
  55.         std::cout<<r[i]<<" ";  
  56.     std::cout<<std::endl;  
  57.     system("pause");  
  58.     return 0;  
  59. }  

 

和以往的代码有些类似,这里还有一些辅助的二维数组p用来回溯最长的这个subsequence.这整个算法的时间复杂度达到了O(n∧2).当然存在一些nlog(n)的实现.但不是动态规划的重点,这里就不说明了.

重点可以讲的是这个问题的扩展.下面的两个问题也是很经典的问题.

问题1.造桥问题. 原题是这样:Building Bridges. Consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-coordinates a(1) ... a(n) and n cities on the northern bank with x-coordinates b(1) ... b(n). You want to connect as many north-south pairs of cities as possible with bridges such that no two bridges cross. When connecting cities, you can only connect city i on the northern bank to city i on the southern bank. (Note: this problem was incorrectly stated on the paper copies of the handout given in recitation.)

大致就是要在一条河的南北两边的各个城市之间造若干座桥.桥两边的城市分别是a(1)...a(n)和b(1)...b(n).这里的要求a(i)只可以和b(i)之间造桥,同时两座桥之间不能交叉.希望可以得到一个尽量多座桥的方案.

图示说明

比如上面这张图,初看上去让人有些没有思路.但是仔细一想,其实这就是一个完美的最长公共子序列的问题的变形.怎么讲呢?如果把河南边的a城市做一个排序,可以得到一个序列.如上图,我们得到的就是S1 = {2,1,3,5,4}在这里,同时北边也进行依次排序,得到序列S2 = {1,2,5,4,3}.进一步从南边的第一座桥开始计算在北边序列中的index.也就是S1中的每个值相对于S2中的位置.比如说A2在南边是第一个在北边是第二个,所以第一个元素是2.A1在北边的对应位置是1.A3在北边的对应位置是5,A5在北边的对应位置是3,最后一个A4在北边的对应位置是3.这样我们就得到一个新的序列S3= {2,1,5,3,4}.这个序列的实际意义就是南边的第几座桥需要连接到北边的第几座桥.做理想的情况就是递增的,那样所有的桥都可以建造:)也就是说我们的造桥问题就转化成了寻找这个序列的最长递增子序列的问题.当然就是{1,3,4}.也就是红线所代表的桥.

代码不贴了,但是问题确实比较奥妙.

问题2.Box Stacking. You are given a set of n types of rectangular 3-D boxes, where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers). You want to create a stack of boxes which is as tall as possible, but you can only stack a box on top of another box if the dimensions of the 2-D base of the lower box are each strictly larger than those of the 2-D base of the higher box. Of course, you can rotate a box so that any side functions as its base. It is also allowable to use multiple instances of the same type of box.

这个问题的简要描述就是有若干个不同的箱子.你需要把他叠放的尽量的高.但是箱子的摆放必须满足大的在下面,小的在上面的原则.箱子可以旋转且数量不限.要求给出一组箱子就能求出能摆放的最大高度. 其实这个问题也是一个最长递增子序列的问题.只是隐藏的更深一点. 因为箱子可以翻转的缘故.我们首先定义我们的箱子的长宽高分别是h,w,d.为了避免重复计算,我们约定w<=d.这样每个箱子可以改成3个箱子.这样我们就不用在考虑旋转的问题了.第一步,我们先把箱子按照w*d的值来排序.(为社么要排序读者可以自己想想).然后我们的模型就开始用H(j)来表示第j个箱子时这个箱子的高度.记得最长递增子序列的约束条件是Ai<Aj.这里的条件只是改成了对应的di<dj&&wi<wj.同时原来的+1也变成了+hi.

最后贴一下不是很好的代码.但是大致上还是工作了:

  1. // box_stacking.cpp : Defines the entry point for the console application.  
  2. //  
  3. #include "stdafx.h"  
  4. #include <iostream>  
  5. #include <vector>  
  6. #include <algorithm>  
  7. #include <functional>   
  8. #include "windows.h"  
  9. /* 
  10. Box Stacking. You are given a set of n types of rectangular 3-D boxes,  
  11. where the i^th box has height h(i), width w(i) and depth d(i) (all real numbers).  
  12. You want to create a stack of boxes which is as tall as possible,  
  13. but you can only stack a box on top of another box if the dimensions of the 2-D base of  
  14. the lower box are each strictly larger than those of the 2-D base of the higher box.  
  15. Of course, you can rotate a box so that any side functions as its base.  
  16. It is also allowable to use multiple instances of the same type of box.  
  17. */  
  18. struct Box  
  19. {  
  20.     int h; // height;  
  21.     int w; // width;  
  22.     int d; // depth;  
  23. };  
  24. struct sizeSort: public std::binary_function <Box, Box, bool>  
  25. {  
  26.     bool operator()(const Box& b1, const Box& b2)  
  27.     {  
  28.         return b1.w*b1.d > b2.w*b2.d;  
  29.     }  
  30. };   
  31. int highest_box_stacking( const std::vector<Box>& b)  
  32. {  
  33.     // first make the box 1*2*3  
  34.     // to like this: 1*(2*3), 2*(1*3), 3*(1*2);  
  35.     // let's assume width<=depth, then we can get 3*n boxes.  
  36.     if (b.size()<1)   
  37.         return 0;  
  38.     std::vector<Box> box (b.size()*3);   
  39.     for (int i=0;i<b.size();i++)  
  40.     {  
  41.         box[i*3+0].h = b[i].h;  
  42.         box[i*3+0].w = b[i].w < b[i].d ? b[i].w : b[i].d;                          
  43.         box[i*3+0].d = b[i].w < b[i].d ? b[i].d : b[i].w;                          
  44.         box[i*3+1].h = b[i].w;  
  45.         box[i*3+1].w = b[i].h < b[i].d ? b[i].h : b[i].d;                          
  46.         box[i*3+1].d = b[i].h < b[i].d ? b[i].d : b[i].h;                          
  47.         box[i*3+2].h = b[i].d;  
  48.         box[i*3+2].w = b[i].h < b[i].w ? b[i].h : b[i].w;                          
  49.         box[i*3+2].d = b[i].h < b[i].w ? b[i].w : b[i].h;      
  50.     }  
  51.     std::sort(box.begin(),box.end(),sizeSort());  
  52.       
  53.     std::vector <int> m(b.size()*3);  
  54.     m[0] = box[0].h;  
  55.     for ( int i = 1; i < box.size(); i++ )  
  56.     {  
  57.         for ( int j = 0; j < i; j++ )  
  58.         {  
  59.             if ( (box[i].w <= box[j].w) && (box[i].d <= box[j].d) && (m[i] < m[j]+box[i].h) )  
  60.                 m[i] = m[j] + box[i].h;  
  61.         }  
  62.     }     
  63.     return *std::max_element(m.begin(),m.end());  
  64. }  
  65. int _tmain(int argc, _TCHAR* argv[])  
  66. {     
  67.     std::vector<Box> box(3);  
  68.     box[0].h = 2;  
  69.     box[0].w = 3;  
  70.     box[0].d = 4;  
  71.     box[1].h = 2;  
  72.     box[1].w = 3;  
  73.     box[1].d = 1;  
  74.     box[2].h = 5;  
  75.     box[2].w = 3;  
  76.     box[2].d = 4;  
  77.     std::cout<<highest_box_stacking(box)<<std::endl;  
  78.     system("pause");  
  79.     return 0;  
  80. }  

 

posted on 2011-04-23 16:54 pp_zhang 阅读(892) 评论(0)  编辑 收藏 引用 所属分类: acm


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理