NY 单调递增最长子序列(一)

时间限制: 3000 ms  |  内存限制: 65535 KB
难度: 4
描述
求一个字符串的最长递增子序列的长度
如:dabdbf最长递增子序列就是abdf,长度为4
输入
第一行一个整数0<n<20,表示有n个字符串要处理
随后的n行,每行有一个字符串,该字符串的长度不会超过10000
输出
输出字符串的最长递增子序列的长度
样例输入
3
aaa
ababc
abklmncdefg
样例输出
1
3

7

思路:LIS的一个简单应用;代码如下:

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int main(){
	int n;
	cin>>n;
	while(n--){
		int i,j,ans=0,dp[100001];
		char a[100001];
		cin>>a;
		int l=strlen(a);
		memset(dp,0,sizeof(dp));
		for(i=0;i<l;i++){
			for(j=0;j<i;j++){
				if(a[i]>a[j])
				   dp[i]=max(dp[i],dp[j]+1);
			}
			ans=max(ans,dp[i]);
		}
		cout<<ans+1<<endl;
	}
	return 0;
}
下面再贴上一个特殊的LIS序列,题是
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

Input

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.

The second line contains n integers pi (1 ≤ pi ≤ npi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Output

Print a single integer — the minimum number of actions needed to sort the railway cars.

Examples
input
Copy
5
4 1 2 5 3
output
Copy
2
input
Copy
4
4 1 3 2
output
Copy
2
Note

In the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

这个LIS的特殊之处在于和上面的代码不同之处在于这个是单调递增子序列,等差为1,可以这样想,先求出最长单调递增子序列,然后用总的减去这个最长的就可以了,思路来源于博客 

很奇怪,这道题竟然不能用

for(i=0;i<l;i++){
			for(j=0;j<i;j++){
				if(a[i]>a[j])
				   dp[i]=max(dp[i],dp[j]+1);
			}
			ans=max(ans,dp[i]);
		}
这样类似的方法解决,很郁闷呀! 先贴上代码

代码如下:

#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	int a[100010];
	int dp[100010];
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
		cin>>a[i];
	for(int i=0;i<n;i++)
	  dp[a[i]]=dp[a[i]-1]+1;  //这一步的作用依次求出dp[]中每个a[]的单调子序列的长度(等差为1) 
	int ans=0;
	for(int i=0;i<n;i++)
	  ans=max(ans,dp[a[i]]);  //选出最长的,用ans记录一下即可 
	cout<<n-ans<<endl;      //总的减去最长的就是需要移动的最少次数 
	return 0;
} 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值