最长递增子序列

1.最长递增子序列(Longest Increasing Subsequence,LIS)

\\\text{Longest Increasing Subsequence Recurrence formula:} \\F(1)=1;\\ F(i)=max\lbrace1,F(j)+1|j<i,aj<ai\rbrace;

例:{1,4,3,2,6,5}

F(1) F(2) F(3) F(4) F(5) F(6)
1 2 2 2 3 3

 

 

 

F[i]:表示第i个元素前的最长递增子序列长度

Longest Increasing Subsequence Example's Code: 

#include 
#include 
#include 
using namespace std;
int main(){
	vector a(26,0);
	vector dp(26,0);
	int n;
	dp[1]=1;
	while(cin>>n){
		for(int i=1;i<=n;i++)
			cin>>a[i];
		for(int i=2;i<=n;i++){
			int mdp=1;
			for(int j=i-1;j>=1;j--)
				if(a[j]<=a[i])
					mdp=max(mdp,dp[j]+1);
			dp[i]=mdp;
		}
		for(int i=1;i<=n;i++)
			cout<

*扩展(最长递减子序列(Longest Diminishing Subsequence)

\\\text{Longest Diminishing Subsequence Recurrence formula:} \\F(1)=1;\\ F(i)=max\lbrace 1,F(j)+1|j<i,aj>ai\rbrace;

例:{300,207 ,155 ,300 ,299 ,170, 158, 65}

F(1) F(2) F(3) F(4) F(5) F(6) F(7) F(8)
1 2 3 2 3 4 5 6

Longest Diminishing Subsequence Example's Code:

#include 
#include 
#include 
using namespace std;
int main(){
	vector a(26,0);
	vector dp(26,0);
	int n;
	while(cin>>n){
		for(int i=1;i<=n;i++)
			cin>>a[i];
		dp[1]=1;
		for(int i=2;i<=n;i++){
			int mdp=1;
			for(int j=i-1;j>=1;j--){
				if(a[j]>=a[i]){
					mdp=max(mdp,dp[j]+1);
				}
			}
			dp[i]=mdp;
		}
		for(int i=1;i<=n;i++)
			cout<

 

 

你可能感兴趣的:(Algorithms,动态规划,最长递增子序列)