C++ OJ HDU 1159 Common Subsequence

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.

样例输入

样例输出

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

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))就得到所要求的解了.
其实自己还有一种想法不过也和这个差不多
  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

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

下面贴代码

 

你可能感兴趣的:(c语言,数据结构,ACM,OJ,C++,OJ)