DFS, unlimited TLE, and ugly code
// Version 1 TLE # include
# Include
# Include
# Define MAX_INT 2147483647 # define MAXN 105 using namespace std; int Map [5] [5] = {0,-3,-4,-2,-1 }, {-3, 5,-1,-2,-1}, {-4,-,-3,-2}, {-2,-2, -2}, {-1,-1,-2,-2, 5},}; int seq1 [MAXN], seq2 [MAXN], Max, n1, n2; int ref (char c) {switch (c) {case 'A': return 1; case 'C': return 2; case 'G': return 3; case 'T': return 4 ;}} void dfs (int id1, int id2, int sum) {if (id2 <= n2 + 1) {if (id2 = n2 + 1) {for (int I = id1; I <= n1; I ++) sum + = Map [seq1 [I] [0]; Max = max (Max, sum); return;} int limi = n1-n2 + id2, tsum = sum; for (int I = id1; I <= limi; I ++) {if (I> id1) tsum + = Map [seq1 [I-1] [0]; dfs (I + 1, id2 + 1, tsum + Map [seq1 [I] [seq2 [id2]) ;}} int main () {freopen (". /1080.in", "r", stdin); int T, I, j; char c; cin> T; while (T --) {scanf ("% d % c ", & n1, & c); for (I = 1; I <= n1; I ++) {scanf ("% c", & c ); seq1 [I] = ref (c);} scanf ("% d % c", & n2, & c); for (I = 1; I <= n2; I ++) {scanf ("% c", & c); seq2 [I] = ref (c);} if (n1 <n2) {for (int I = 1; I <= n1; I ++) swap (seq1 [I], seq2 [I]); for (int I = n1 + 1; I <= n2; I ++) seq1 [I] = seq2 [I]; swap (n1, n2);} Max =-MAX_INT; dfs (1, 1, 0 ); cout <
After that, I thought for a long time. I didn't think of the transformed LCS (longest common subsequence) in the two sequences. I just tried to write the state transition equation, finally, the dp [I] [j] = max (dp [I-1] [J-1] ''', dp [I-1] [j] ''', dp [I] [J-1] '''), then a look to understand this is LCS idea, but at the beginning is indeed blind write, may happen =. =. Finally, pay attention to this situation: dp [0] [x]. When a sequence is supplemented with 0, there is no way to get results in the loop process. It can only be done in advance. Remember!
/*poj 1080268K0MS*/#include
#include
#include
#define MAXN 105#define MAX_INT 2147483647using namespace std;int Map[5][5] = {{0,-3,-4,-2,-1},{-3,5,-1,-2,-1},{-4,-1,5,-3,-2},{-2,-2,-3,5,-2},{-1,-1,-2,-2,5},};int seq1[MAXN],seq2[MAXN],dp[MAXN][MAXN],n1,n2;int ref(char c){switch (c){case 'A':return 1;case 'C':return 2;case 'G':return 3;case 'T':return 4;}}int calc(){memset(dp , 0 , sizeof(dp));for(int i = 1;i <= n1;i ++)dp[i][0] = dp[i-1][0] + Map[seq1[i]][0];for(int i = 1;i <= n2;i ++)dp[0][i] = dp[0][i-1] + Map[0][seq2[i]];for(int i = 1;i <= n1;i ++)for(int j = 1;j <= n2;j ++)dp[i][j] = max(dp[i-1][j-1] + Map[seq1[i]][seq2[j]] ,max(dp[i-1][j] + Map[seq1[i]][0] , dp[i][j-1] + Map[0][seq2[j]]) );return dp[n1][n2];}int main(){int T,i,j;char c;cin>>T;while(T --){scanf("%d%c",&n1,&c);for(i = 1;i <= n1;i ++){scanf("%c",&c);seq1[i] = ref(c);}scanf("%d%c",&n2,&c);for(i = 1;i <= n2;i ++){scanf("%c",&c);seq2[i] = ref(c);}cout<