Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
也可以都反过来,弄2个first数组,dp求最长LCS长度时从后往前递推(用于dfs时减枝),求所有LCS时顺着走,每位从a试到z,这样,就不用排序了……In Reply To:转个解题报告。。 Posted by:damacheng009 at 2010-11-21 21:33:31 #include <stdio.h> #include <string.h> #define STR_LEN 81 #define NUM_LCS 1000 int dp[STR_LEN][STR_LEN], first_a[STR_LEN][26], first_b[STR_LEN][26], la, lb, lcs_len, num_lcs; char sa[STR_LEN], sb[STR_LEN], tmp[STR_LEN], lcs[NUM_LCS][STR_LEN]; int get_len() { int i, j; for(i = la - 1; i >= 0; i--) { for(j = lb - 1; j >= 0; j--) { if(sa[i] == sb[j]) dp[i][j] = dp[i + 1][j + 1] + 1; else dp[i][j] = dp[i + 1][j] > dp[i][j + 1] ? dp[i + 1][j] : dp[i][j + 1]; } } return dp[0][0]; } void get_first(char *s, int first[][26], int len) { int i, j; for(i = 0; i < 26; i++) first[len][i] = -1; for(i = len - 1; i >= 0; i--) { for(j = 0; j < 26; j++) first[i][j] = first[i + 1][j]; first[i][s[i] - 'a'] = i; } } void dfs(int ia, int ib, int id) { int i, nid = id + 1; if(id == lcs_len) { strcpy(lcs[num_lcs++], tmp); return; } if(dp[ia][ib] + id < lcs_len || ia >= la || ib >= lb) return; for(i = 0; i < 26; i++) { if(first_a[ia][i] >= 0 && first_b[ib][i] >= 0) { tmp[id] = i + 'a'; dfs(first_a[ia][i] + 1, first_b[ib][i] + 1, nid); } } } int main() { int i, j, k, end; scanf("%s%s", sa, sb); la = strlen(sa); lb = strlen(sb); lcs_len = get_len(); get_first(sa, first_a, la); get_first(sb, first_b, lb); dfs(0, 0, 0); for(i = 0; i < num_lcs; i++) printf("%s\n", lcs[i]); return 0; } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator