Monotonically increasing longest subsequence
Time Limit:
3000
ms | Memory Limit:
65535
KB
Difficulty:
4
- describe
-
Find the length of the longest increasing subsequence of a string
For example : dabdbf The longest increasing subsequence is abdf, with a length of 4
- enter
-
The first line contains an integer 0<n<20, indicating that there are n strings to be processed.
The next n lines, each line has a string, and the length of the string will not exceed 10000 - output
- the length of the longest increasing subsequence of the output string
- sample input
-
3 aaa ababc abklmncdefg
- Sample output
-
1 3
7
-
The initial idea is to nest two for loops, traversing each letter as the starting point and then getting the smallest value is the answer, but the third test data is according to my idea.
-
abklmn, but the longest should be abcdefg, so I wrote the logic wrong code for an afternoon...
-
#include<iostream> #include<cstring> using namespace std; int main(){ const int MAX = 10005; char s[MAX]; int num[MAX]; int n; cin>>n; while(n--){ memset(s,0,sizeof(s)); cin>>s; int len= strlen(s); memset(num,0,sizeof(num)); int k=0; // for(int i=0;i<len;i++) cout<<num[i]<<" "; cout<<endl; for(int i=0;i<len;i++){ int p=i; int sum=1; for(int j=p+1;j<len;){ if(s[p]<s[j]){ p=j; j++; sum++; }else{ j++; } } num[i]=I // for(int jj=0;jj<len;jj++) cout<<num[jj]<<" "; cout<<endl; } int max = num[0]; for(int i=0;i<len;i++){ if(max<num[i]) max = num[i]; } cout<<max<<endl; } return 0; }
Hey, I checked later and found out that it was a dp question.
-
My idea is to calculate each one as the starting point, what should be thought is to calculate with each one as the focus
-
If it ends with the first one, then the length is 1, if it ends with the second one, then the length is f(2) = max(f(1),f(1)+1)
-
The length is n, f(n) = max( f(n), f(n-1)+1) If n is smaller than n-1, then f(n)=f(n-1), if n>n -1, f(n) = f(n-1)+1
-
#include<iostream> #include<cstring> using namespace std; int main(){ const int MAX = 10005; char s[MAX]; int num[MAX]; int n; cin>>n; while(n--){ memset(s,0,sizeof(s)); cin>>s; int len= strlen(s); for(int jj=0;jj<=len;jj++) num[jj]=1; // for(int i=0;i<len;i++) cout<<num[i]<<" "; cout<<endl; for(int i=1;i<len;i++){ for(int j=0;j<i;j++){ if(s[j]<s[i]&&num[i]<num[j]+1) num[i]=num[j]+1; } // for(int jj=0;jj<len;jj++) cout<<num[jj]<<" "; cout<<endl; } int max = num[0]; for(int i=0;i<len;i++){ if(max<num[i]) max = num[i]; } cout<<max<<endl; } return 0; }
-
-
-