Longest Ordered Subsequence
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 34454 | Accepted: 15135 |
Description
A numeric sequence of ai is ordered if a1 < a2 < ... <aN. Let the subsequence of the given numeric sequence (a1,a2, ...,aN) be any sequence (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 of length 4, e. g., (1, 3, 5, 8).
Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.
Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.
Input
The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000
Output
Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence.
Sample Input
7
1 7 3 5 9 4 8
Sample Output
4
本题是一道经典的DP动态规划问题,求最长上升子序列,序列不一定要连续,但是如果是求子串的情况就要求连续,用题目的样例来说说思路,只要找出动态转移方程此题就迎刃而解了,外层循环i遍历整个数组,内层循环j遍历i之前的数,只要找到j小于i,即A[j] < A[i],便可以+1,写出状态转移方程max(1,d[j]+1) + 1,所以置a[i]初始化为1,每次更新a[i]即可,最后比较每个a[i],最大的即为要求的结果。下面为代码:
/*
Title : Longest Ordered Subsequence
Author : minisheep
Running time:47MS
Memory cost:224K
*/
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 1001;
int a[maxn],m;
int dp[maxn];
int LIS()
{
int i,j,temp;
temp = 1;
for(i=1;i<=m;i++)
{
dp[i] = 1;
for(j=1;j<i;j++)
{
if(a[j]<a[i] && dp[j] + 1 > dp[i]) //刚开始的时候写成a[j]<= a[i] ,WA了几次,没看清题意,如果题意是求非下降子序列就要等于
{
dp[i] = dp[j] + 1;
//cout<<dp[i]<<endl;
}
}
if(dp[i] > temp)
{
temp = dp[i];
//cout<<temp<<endl;
}
}
return temp;
}
int main()
{
int i,cnt;
//freopen("1.in","r",stdin);
while(cin>>m)
{
for(i=1;i<=m;i++)
{
cin>>a[i];
}
cnt = LIS();
cout<<cnt<<endl;
}
}
---------------------------------------------------
时隔半年后(2015-07-11),用单调队列+二分(时间复杂度nlogn)再度AC本题,一共跑了16ms.时间降了一倍多.
解题思路:
一个一个元素插入队列,如果发现后者比当前的队尾元素大那么插入队尾,否则二分查找到比他大的最小值那个位置,替换掉即可。
代码如下:
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 1005;
int Binary_Search(int *a,int left,int right,int element)
{
int l = left;
int r = right;
int mid;
while(l < r)
{
mid = (l + r) / 2;
if(a[mid] <= element) l = mid + 1;
else
r = mid;
}
return l;
}
int main()
{
int m;
int i;
while(cin>>m)
{
int t;
int cnt;
int a[maxn];
cnt = 0;
scanf("%d",&a[0]);
cnt++; //一个元素插入队列
//cout<<cnt<<endl;
for(i=1;i<m;i++)
{
scanf("%d",&t);
if(t > a[cnt-1])
{
a[cnt++] = t;
}
else
{
a[Binary_Search(a,0,cnt,t)] = t;
}
}
printf("%d",cnt);
}
return 0;
}