C++ OJ HDU 1159 Common Subsequence

来源:互联网 发布:积分入学社保怎么算法 编辑:程序博客网 时间:2024/05/01 00:14
C++ OJ 

HDU 1159 Common Subsequence

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.

样例输入

样例输出

 abcfbca111111b122222f122333c123334a123334b123344

大概就是画这样一个表格,动态规划的方式去解题

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]);

n由于F(i,j)只和F(i-1,j-1), F(i-1,j)和F(i,j-1)有关, 而在计算F(i,j)时, 只要选择一个合适的顺序, 就可以保证这三项都已经计算出来了, 这样就可以计算出F(i,j). 这样一直推到f(len(a),len(b))就得到所要求的解了.
其实自己还有一种想法不过也和这个差不多
 abcfbca100000b010010f000100c001001a100000b010010

算法是只能往下,然后找到一个出表格的最长的路,其实本质上差不多

下面贴代码

 

0 0
原创粉丝点击