[动态规划]之裸lis之最长上升子序列POJ 2533
2016-05-16 22:26
399 查看
一、乱喷
昨天华中农业大学网赛,又是只写了写水题,还发生了些戏剧性的事情。最后一题没时间看,今天看了看,本来想写,发现考的是最长上升等差子序列数列的长度,递增的还不会,就问了问宋大神,就先看了看最长上升子序列。二、Lis
时间复杂度(n^2) ----(优化方法回头补上)我的理解:例子 a[i] 标号从1-n;
{2,1,5,3,6,4,8}
dp[i]数组存的是 第i个数的最长上升子序列的长度。
步骤:
1.对于{2}来说,dp[1]=1,也就是最长上升子序列长度为1.
2.对于{2,1},首先我们比较a[1]与a[2]大小
若a[1]>a[2] ,此时一个最长子序列的长度仍然为1,即dp[2]=1.
若a[1]<a[2],则可以看出a[1],a[2] 是递增的,所以dp[2]=dp[1]+1;
3.对于{2,1,5}
这时候a[3]要分别与a[1],a[2] 比较大小。
a[3]>a[1],由于子序列可以是不连续的,故{a[1],a[3]}可以是一个子序列,dp[3]=dp[1]+1
a[3]>a[2],说明以a[2]为末端的子序列(可以不连续哦)+a[3]能形成一个新的子序列,此时要给dp[3]赋值,
重点来了,dp[3]是等于dp[2]+1还是等于dp[1]+1
既然求最长 当然是dp[3]=max(dp[1],dp[2])+1
当 a[3]即小于a[1]又小于a[2]的时候 dp[3]=1
例子中dp[3]=max(dp[1],dp[2])+1=1+1=2;
...
这样问题就可以总结为:
在dp[1],dp[2],dp[3]...dp[n-1]的情况下求dp
若a
>a[1],a
>a[2],a
>a[3]….,
dp
=max{dp[1],dp[2],dp[3],,,,,,}+1
若不满足
dp
=1;
题目:
Longest Ordered Subsequence
Time Limit: 2000 MS Memory Limit: 65536 KB
64-bit integer IO format: %I64d , %I64u Java class name: Main
[Submit] [Status]
[Discuss]
Description
A numericsequence of ai is orderedif a1 < a2 <
...< aN. Let thesubsequence of the given numeric sequence (a1, a2,
..., aN) be anysequence (ai1, ai2,
..., aiK), where 1 <= i1 < i2 <
...< iK <= N.For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g.,(1, 7), (3, 4, 8) and many others. All longest ordered subsequences
are oflength 4, e. g., (1, 3, 5, 8).
Your program, when given the numeric sequence, must find the length of itslongest ordered subsequence.
Input
The first lineof input file contains the length of sequence N. The second line contains theelements of sequence - N integers in the range from 0 to 10000 each, separatedby spaces. 1 <= N <= 1000
Output
Output file mustcontain a single integer - the length of the longest ordered subsequence of thegiven sequence.
Sample Input
7
1 7 3 5 9 4 8
Sample Output
4
Source
NortheasternEurope 2002, Far-Eastern Subregion
AC code
#include<cstdio> #include<string.h> #include<math.h> #include<algorithm> using namespace std; int a[1005],dp[1005]; int lis(int n) { int i,j,max; int ans=1; dp[1]=1; for(i=2;i<=n;i++) { max=0; for(j=1;j<=i;j++) { if(max<dp[j]&&a[j]<a[i]) max=dp[j]; } dp[i]=max+1; //若for(j)中的条件不成立。也就是说a[i]比前边的数都大 所以dp[i]=0+1; if(dp[i]>ans) ans=dp[i]; } return ans; } int main() { int t,i; while(scanf("%d",&t)!=EOF) { memset(dp,0,sizeof(a)); for(i=1;i<=t;i++) scanf("%d",a+i); int ans=lis(t); printf("%d\n",ans); } return 0; }
相关文章推荐
- Java中补码的规则
- osg布告板技术(Billboard)
- getRequestDispatcher ,sendRedirect
- 测试并发编程demo
- 求成绩
- hdoj 5681 zxa and wifi
- MySQL:Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEM
- shell脚本的使用---if变量编写lamp管理脚本
- hdu_4824_Disk Schedule(dp)
- QT信号槽多次连接引起的错误修改
- mybatis查询没有返回结果,程序不继续执行
- javascript基础-黑白反斗棋
- 使用Jmeter进行http接口测试
- centos 的权限管理--自主访问控制DAC和访问控制列表 ACL
- hdu_4824_Disk Schedule(dp)
- 提高Java代码质量的Eclipse插件之Checkstyle的使用详解
- 作业8:单元测试练习(个人练习)
- 【Gym 100971A】Treasure Island
- LaTeX技巧001:ctex下使用其他中文字体
- iOS多线程