最长有序子序列(DP + 记录路径)

来源:互联网 发布:软件健壮性例子 编辑:程序博客网 时间:2024/05/29 11:14

在这个题目中,上升序列,很容易.直接上代码吧。

模块一:最长有序子序列,求出最长序列的长度。
方法一:
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX 10000int main(void){int n, a[MAX], dp[MAX], max;while(scanf("%d", &n) == 1){memset(a, 0, sizeof(a));memset(dp, 0, sizeof(dp));max = 0;for(int i = 1; i <= n; i++){scanf("%d", &a[i]);dp[i] = 1;}for(int i = 1; i <= n; i++)for(int j = 1; j < i; j++){if(a[i] > a[j] && dp[i] < dp[j] + 1){dp[i] = dp[j] + 1;if(dp[i] > max)max = dp[i];}}printf("%d\n", max);}return 0;}

方法二:将原序列进行排序,然后将排序后的序列与原序列寻找公共子序列。
#include <stdio.h>#include <stdlib.h>#include <string.h> #define MAX 10000int cmp(const void *a, const void *b){return *(int *)a - *(int *)b; } int n, a[MAX], b[MAX], dp[MAX][MAX], max;//a[i]记录原序列,b[i]记录排序后的序列 int main(void){while(scanf("%d", &n) == 1){memset(a, 0, sizeof(a));memset(dp, 0, sizeof(dp));for(int i = 1; i <= n; i++)   {   scanf("%d", &a[i]);   b[i] = a[i];   }qsort(b, n, sizeof(b[1]), cmp); for(int i = 1; i <= n; i++)for(int j = 1; j <= n; j++){if(b[i] == a[j])dp[i][j] = dp[i -1][j - 1] + 1;elsedp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1]; } printf("%d\n", dp[n][n]); } return 0;}

模块二:最长有序序列,记录路径。
#include<stdio.h>#define MAX 1000000int a[MAX];int len[MAX];int pre[MAX];int last = 0;int stack[MAX];int top = 0;void init(int n){for(int i=0; i<n; i++){len[i] = 1;pre[i] = i;last = 0;top = 0;}}int main(){int i, j;int n;while(scanf("%d", &n) != EOF){for(i=0; i<n; i++){scanf("%d", &a[i]);}//initinit(n);// solvefor(i=0; i<n; i++){int lmax = 1;for(j=i-1; j>=0; j--){if(a[i] >= a[j]){if(len[j] + 1 > lmax){lmax = len[j] + 1;len[i] = len[j] + 1;pre[i] = j;last = i;printf("%d->%d\n", i, j);}}}}//printf("%d \n", last);// outputwhile(pre[last] != last){stack[top++] = a[last];last = pre[last];}stack[top++]  = a[last];for(i=top-1; i>=0; i--){printf("%d ", stack[i]);}printf("\n");}return 0;}
上面是别人的代码。下面为我自己语言风格,写的代码。
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX 10000int main(void){int n, top, last, stack[MAX], a[MAX], dp[MAX], pre[MAX];while(scanf("%d", &n) == 1){memset(a, 0, sizeof(a));memset(dp, 0, sizeof(dp));memset(stack, 0, sizeof(stack));last = 1;top = 0;for(int i = 1; i <= n; i++){scanf("%d", &a[i]);dp[i] = 1;pre[i] = i;}for(int i = 1; i <= n; i++){int max = 1;for(int j = 1; j < i; j++)if(a[i] > a[j] && max < dp[j] + 1){dp[i] = dp[j] + 1;max = dp[j] + 1;pre[i] = j;last = i;//printf("%d -> %d\n", i, j);}}//printf("%d\n", last);while(pre[last] != last){stack[top++] = a[last];last = pre[last];}stack[top++] = a[last];for(int i = top - 1; i >= 0; i--)printf("%d ", stack[i]);printf("\n");}return 0;}


0 0
原创粉丝点击