思路1
\(f_{i,j}\)表示放入\(i\)原料,并且当前锅中有\(j\)个原料。
状态转移方程:\(f_{i,j}=\underset{j - 1\le k\le \min \lbrace j + s - 1\rbrace}\max\lbrace f_{i-1,k} + a_i \times j\rbrace\)
代码1
#include <iostream>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 5010;
int n,w,s;
LL a[N];
LL f[N][N];
int main () {
cin >> n >> w >> s;
for (int i = 1;i <= n;i++) cin >> a[i];
memset (f,-0x3f,sizeof (f));
f[0][0] = 0;
for (int i = 1;i <= n;i++) {
for (int j = 1;j <= w;j++) {
for (int k = j - 1;k <= min (w,j + s - 1);k++) f[i][j] = max (f[i][j],f[i - 1][k] + j * a[i]);
}
}
LL ans = -1e18;
for (int i = 0;i <= w;i++) ans = max (ans,f[n][i]);
// for (int i = 1;i <= n;i++) {
// for (int j = 0;j <= w;j++) cout << f[i][j] << ' ';
// cout << endl;
// }
// cout << endl;
cout << ans << endl;
return 0;
}
思路2
公式一拆变为\(f_{i,j}=\underset{j - 1\le k\le \min \lbrace j + s - 1\rbrace}\max\lbrace f_{i-1,k} \rbrace+ a_i \times j\)
我们用单调队列\(O(1)\)查询f_{i - 1,k}的最大值。
代码2
#include <iostream>
#include <cstring>
#include <deque>
using namespace std;
typedef long long LL;
const int N = 5010;
int n,w,s;
LL a[N];
LL f[N][N];
int main () {
cin >> n >> w >> s;
for (int i = 1;i <= n;i++) cin >> a[i];
memset (f,-0x3f,sizeof (f));
f[0][0] = 0;
for (int i = 1;i <= n;i++) {
deque <int> q;
q.push_back (w);
for (int j = w;j >= 1;j--) {
while (q.size () && q.front () - j >= s) q.pop_front ();
while (q.size () && f[i - 1][q.back ()] <= f[i - 1][j - 1]) q.pop_back ();
q.push_back (j - 1);
f[i][j] = f[i - 1][q.front ()] + a[i] * j;
}
}
LL ans = -1e18;
for (int i = 0;i <= w;i++) ans = max (ans,f[n][i]);
// for (int i = 1;i <= n;i++) {
// for (int j = 0;j <= w;j++) cout << f[i][j] << ' ';
// cout << endl;
// }
// cout << endl;
cout << ans << endl;
return 0;
}
标签:03,le,rbrace,int,LL,SWTR,P5858,long,include
From: https://www.cnblogs.com/incra/p/16859924.html