您的位置:首页 > 其它

最大公共子序列,最大子段和(动态规划)

2017-02-28 20:16 375 查看
最大公共子序列
/*2017.2.28 代文海*/
/*题意简介:求两个字符串的最大公共子序列
思路:设有字符串X和字符串Y, 数组l[i][j]表示字符串的前i个字符和字符串Y的前j个字符构成的最长公共子序列。
如果有X[i] = Y[j]那么有l[i][j]=l[i-1][j-1],否则l[i][j] = max(l[i][j-1], l[i-1][j]).
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1, str2;
int i, j, len1, len2;
int l[101][101] = {0};
cin >> str1>> str2;
len1 = str1.length(), len2 = str2.length();
for(i = 1; i <= len1; i++)
for( j = 1; j <= len2; j++)
if(str1.at(i-1) == str2.at(j-1))
l[i][j] = l[i-1][j-1] + 1;
else
l[i][j] = max(l[i-1][j], l[i][j-1]);
cout<<l[len1][len2]<< endl;
system("pause");
return 0;
}


最大子段和
/* 2017.2.28   代文海*/
/*给一个数列,求数列中的两个不相交的子段,要求字段和最大*/
/* input:10  1 3 -5 6 -2 -1 5 4 -2 -3
output: 16
*/
#include <iostream>
using namespace std;
int main(int arg, char* args[])
{
int i, n;
int a[100], left[100], right[100];
cin>> n;
for( i = 0; i < n; i++)
cin>> a[i];
// left[i] 为包含a[i]的最大子段
left[0] = a[0];
for( i = 1; i < n; i++)
if(left[i-1] >= 0)
left[i] = left[i-1] + a[i];
else
left[i] = a[i];
for( i = 1; i < n; i++)
left[i] = max(left[i], left[i-1]);

right[n-1] = a[n-1];
for( i = n-2; i >= 0; i--)
if(right[i+1] >=0)
right[i] = right[i+1] + a[i];
else
right[i] = a[i];
for( i = n-2; i >= 0 ; i--)
right[i] = max(right[i], right[i+1]);
int answer = -10000;
for(i = 0; i < n-1; i++)
answer = max(answer, left[i] + right[i+1]);
cout<< answer<< endl;
system("pause");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: