CodeForces 148E(动态规划)

来源:互联网 发布:找谱子的软件 编辑:程序博客网 时间:2024/06/01 09:14

问题描述:

During her tantrums the princess usually smashes some collectable porcelain. Every furious shriek is accompanied with one item smashed.

The collection of porcelain is arranged neatly on n shelves. Within each shelf the items are placed in one row, so that one can access only the outermost items — the leftmost or the rightmost item, not the ones in the middle of the shelf. Once an item is taken, the next item on that side of the shelf can be accessed (see example). Once an item is taken, it can't be returned to the shelves.

You are given the values of all items. Your task is to find the maximal damage the princess' tantrum of m shrieks can inflict on the collection of porcelain.

Input

The first line of input data contains two integers n (1 ≤ n ≤ 100) and m (1 ≤ m ≤ 10000). The next n lines contain the values of the items on the shelves: the first number gives the number of items on this shelf (an integer between 1 and 100, inclusive), followed by the values of the items (integers between 1 and 100, inclusive), in the order in which they appear on the shelf (the first number corresponds to the leftmost item, the last one — to the rightmost one). The total number of items is guaranteed to be at least m.

Output

Output the maximal total value of a tantrum of m shrieks.

Example

2 33 3 7 23 4 1 5
15

题目题意:给我们我们n排数字,每排数字m[i]个,我们每次只能从最左端和最右端拿数字,拿走了就消失,问我们拿到的最大的数字和。

题目分析:因为拿数字的限制导致问题变得复杂,我们先处理出每一行拿i个数字的最大和,限制就没有了。

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>using namespace std;const int maxn=1e4+10;int sum[maxn],ma[105][maxn],dp[105][maxn],m[105];int main(){    int n,num;    while (scanf("%d%d",&n,&num)!=EOF) {        for (int i=1;i<=n;i++) {            scanf("%d",&m[i]);            for (int j=1;j<=m[i];j++) {                scanf("%d",&sum[j]);                sum[j]=sum[j-1]+sum[j];            }            for (int k=1;k<=m[i];k++) {                for (int j=0;j<=k;j++) {                    ma[i][k]=max(ma[i][k],sum[j]+sum[m[i]]-sum[m[i]+j-k]);//保存每一行拿k个数字的最大和                }            }        }        for (int i=1;i<=n;i++) {            for (int j=num;j>=1;j--) {//必须逆向,为了避免重复拿数字                for (int k=0;k<=m[i];k++) {                    if (j-k>=0)                       dp[i][j]=max(dp[i][j],dp[i-1][j-k]+ma[i][k]);                }            }        }        printf("%d\n",dp[n][num]);    }    return 0;}