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
Input
2 3
3 3 7 2
3 4 1 5
Output
15
Input
1 3
4 4 3 1 2
Output
9
题意:n个架子,每个架子分别有不同个物品,每个物品对应某个价值,每次只能从每一排的最左或者最右拿,一共要摔坏m个物品。问摔坏的最大价值为多少。先预处理,算出每排分别拿1,2,3......个物品的价值,再对比,最后背包求解,看代码意会意会。。。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
int sum[110],ma[110],dp[100005];
int main()
{
int n,m;
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++){
int num;
scanf("%d",&num);
for(int j=1;j<=num;j++){
int temp;
scanf("%d",&temp);
sum[j]=sum[j-1]+temp;
}
//预处理:
memset(ma,0,sizeof(ma));
for(int j=0;j<=num;j++){
for(int k=0;k<=j;k++){
ma[j]=max(ma[j],sum[k]+sum[num]-sum[num+k-j]);
}//需要意会啊,不懂的列出几个应该就明白了
}
//多重背包:
for(int j=m;j>=1;j--)
for(int k=1;k<=min(j,num);k++)//要小于:num和j更小的那个,因为m可能大于一排的数量(因为开始m=j,即j可能大于num)。
dp[j]=max(dp[j],dp[j-k]+ma[k]);
}//一层一层记录与对比,所以for循环一直到这
printf("%d\n",dp[m]);
}