-
描述
-
求一个字符串的最长递增子序列的长度
如:dabdbf最长递增子序列就是abdf,长度为4
-
输入
-
第一行一个整数0<n<20,表示有n个字符串要处理
随后的n行,每行有一个字符串,该字符串的长度不会超过10000
输出
- 输出字符串的最长递增子序列的长度 样例输入
-
3 aaa ababc abklmncdefg
样例输出
-
1 3
7
-
思路:LIS的一个简单应用;代码如下:
-
下面再贴上一个特殊的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; }
time limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn 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?
InputThe 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 ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.
OutputPrint a single integer — the minimum number of actions needed to sort the railway cars.
ExamplesinputCopy5 4 1 2 5 3
outputCopy2
inputCopy4 4 1 3 2
outputCopy2
NoteIn 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; }