最大連續子序列和/最長不下降子序列/最長公共子序列/最長迴文子串
阿新 • • 發佈:2018-11-10
//最大連續子序列和 #include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 10010; int A[maxn],dp[maxn]; int main(){ int n; cin>>n; for(int i = 1 ; i <= n ; i++) { cin>>A[i]; } dp[0] = 0; for(int i = 1 ; i <= n ; i++) { dp[i]=max(A[i],A[i]+dp[i-1]); } int res=-0x3f3f3f; for(int i = 1 ; i <= n ;i++) { if(dp[i]>res){ res = dp[i]; } } cout<<res; }
//最長不下降子序列 #include<bits/stdc++.h> using namespace std; const int maxn = 10010; int A[maxn],dp[maxn]; int main(){ int n; cin>>n; for(int i = 1 ; i <= n ;i++) { cin>>A[i]; } int res = -1; for(int i = 1 ; i <= n ;i++) { dp[i] = 1; for(int j = 1; j < i ; j++) { if(A[i]>=A[j]&&dp[j]+1>dp[i]) { dp[i] = dp[j] + 1; } } res = max(res,dp[i]); } cout<<res; }
//最長公共子序列 #include<bits/stdc++.h> using namespace std; const int maxn = 10010; char A[maxn],B[maxn]; int dp[maxn][maxn]; int main(){ gets(A+1); gets(B+1);//從下表為1開始讀 int lenA = strlen(A+1); int lenB = strlen(B+1); for(int i = 0 ; i < lenA ; i++) { dp[i][0] = 0; } for(int i = 0 ; i < lenB ; i++) { dp[0][i] = 0; } int res = -1; for(int i = 1; i <= lenA; i++) { for(int j = 1; j <=lenB; j++) { if(A[i]==B[j]){ dp[i][j] = dp[i-1][j-1]+1; res = max(res,dp[i][j]); } else{ dp[i][j] = max(dp[i-1][j],dp[i][j-1]); } } } //cout<<res; cout<<dp[lenA][lenB]; }
//最長迴文子串
#include<bits/stdc++.h>
using namespace std;
const int maxn = 10010;
char S[maxn];
int dp[maxn][maxn];//dp表示S[I]到S[J]的子串是否是迴文字串,是為1,不是為0;
int main(){
gets(S);
int len = strlen(S);
int ans = 1;
memset(dp,0,sizeof(dp));
//邊界
for(int i = 0 ; i < len ; i++)
{
dp[i][i] = 1;
if(i < len - 1)
{
if(S[i]==S[i+1]){
dp[i][i+1] = 1;
ans = 2;
}
}
}
//狀態轉移方程
for(int L = 3; L <= len; L++)
{
for(int i = 0 ; i+L-1 < len; i++)
{
int j = i+L-1;
if(S[i]==S[j]&&dp[i+1][j-1]==1){
dp[i][j]=1;
ans = L;
}
}
}
cout<<ans;
}