E. Porcelain
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
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.
Examples
input
Copy
2 3 3 3 7 2 3 4 1 5
output
Copy
15
input
Copy
1 3 4 4 3 1 2
output
Copy
9
Note
In the first case there are two shelves, each with three items. To maximize the total value of the items chosen, one can take two items from the left side of the first shelf and one item from the right side of the second shelf.
In the second case there is only one shelf, so all three items are taken from it — two from the left side and one from the right side.
大意:有n个书架,每次取书只能从书架两端开始取,取m本书,问价值最大为多少
思路:
先预处理maxx[i][j] 即第i层拿j本书的最大价值
然后再dp 转移方程:dp[i][j]=max(dp[i][j],dp[i-1][j-k]+maxx[i][k]) 表示前i层放j本书的最大价值=dp 前i-1层放j-k本书 + maxx 第i层放k本书
#include <cstdio>
#include <algorithm>
#include <math.h>
#include <string.h>
#include <vector>
#include <iostream>
#define ll long long
#define INF 0x3f3f3f
using namespace std;
const int N=10000010;
int sum[111];
int maxx[111][111];
int dp[111][11111];
int cnt[111];
int main()
{
int n,m,i,j,k,x,y;
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
{
scanf("%d",&x);
cnt[i]=x;
for(j=1;j<=x;j++)
{
scanf("%d",&y);
sum[j]=sum[j-1]+y;
}
for(j=1;j<=x;j++)
for(k=0;k<=j;k++)
maxx[i][j]=max(maxx[i][j],sum[k]+sum[x]-sum[x-(j-k)]);
}
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
for(k=0;k<=cnt[i];k++)
if(j-k>=0)
dp[i][j]=max(dp[i][j],dp[i-1][j-k]+maxx[i][k]);
printf("%d\n",dp[n][m]);
}