Now I think you have got an AC in Ignatius.L’s “Max Sum” problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.
Given a consecutive number sequence S1, S2, S3, S4 … Sx, … Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + … + Sj (1 ≤ i ≤ j ≤ n).
Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i1, j1) + sum(i2, j2) + sum(i3, j3) + … + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jxis not allowed).
But I`m lazy, I don’t want to write a special-judge module, so you don’t have to output m pairs of i and j, just output the maximal summation of sum(ix, jx)(1 ≤ x ≤ m) instead. ^_^
输入
Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 … Sn.
Process to the end of file.
输出
Output the maximal summation described above in one line.
样例输入
样例输出
| a | b | c | f | b | c | |
| a | 1 | 1 | 1 | 1 | 1 | 1 |
| b | 1 | 2 | 2 | 2 | 2 | 2 |
| f | 1 | 2 | 2 | 3 | 3 | 3 |
| c | 1 | 2 | 3 | 3 | 3 | 4 |
| a | 1 | 2 | 3 | 3 | 3 | 4 |
| b | 1 | 2 | 3 | 3 | 4 | 4 |
大概就是画这样一个表格,动态规划的方式去解题
F[i][j]=F[i-1][j-1]+1;(a[i]==b[j])
F[i][j]=max(F[i-1][j],F[i][j-1])(a[i]!=b[j]);
| a | b | c | f | b | c | |
| a | 1 | 0 | 0 | 0 | 0 | 0 |
| b | 0 | 1 | 0 | 0 | 1 | 0 |
| f | 0 | 0 | 0 | 1 | 0 | 0 |
| c | 0 | 0 | 1 | 0 | 0 | 1 |
| a | 1 | 0 | 0 | 0 | 0 | 0 |
| b | 0 | 1 | 0 | 0 | 1 | 0 |
算法是只能往下,然后找到一个出表格的最长的路,其实本质上差不多
下面贴代码

本文介绍了一道经典的动态规划题目——HDU1159 Common Subsequence,并提供了详细的解题思路及代码实现。通过构建二维数组记录最长公共子序列长度,逐步解析如何找出两个字符串之间的最长公共子序列。
1658

被折叠的 条评论
为什么被折叠?



