两道基础动态规划poj1458最长公共子序列和poj2533最长上升序列
http://poj.org/problem?id=1458
#include <stdio.h> #include <iostream> #include <string> #define max(a,b) ((a) > (b) ? (a) : (b)) using namespace std; #define MAX 1000 int dp[MAX][MAX];//dp[i][j]表示s1前i个字符组成的substring与s2前j个字符组成的substring的最长公共子序列长度 int main(int argc, const char *argv[]) { string s1, s2; while(cin >> s1 >> s2){ int len1 = s1.length(); int len2 = s2.length(); int len = max(len1, len2); //memset(dp, 0, sizeof(dp)); for (int i = 0; i < len; i++) { dp[0][i] = 0; dp[i][0] = 0; } for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { if (s1[i - 1] == s2[j - 1]) {//test the ith char of s1& jth of s2 dp[i][j] = 1 + dp[i - 1][j - 1]; }else{ dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]); } } } printf("%d\n", dp[len1][len2]); } return 0; }
http://poj.org/problem?id=2533
#include <stdio.h> #include <iostream> #include <string> #define max(a,b) ((a) > (b) ? (a) : (b)) using namespace std; #define MAX 1005 int dp[MAX];//dp[i]表示以a[i]结尾的最长上升序列的长度 int a[MAX]; int main(int argc, const char *argv[]) { int N; cin >> N; for (int i = 0; i < N; i++) { scanf("%d", a + i); dp[i] = 1; } int max = 1; for (int i = 1; i < N; i++) { for (int j = i - 1; j >= 0; j--) { if (a[i] > a[j] && dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; } } if(max < dp[i]) max = dp[i]; } printf("%d\n", max);//这里不是dp[N - 1]....犯了一个愚蠢的错误 return 0; }