题意: 给定p,q,r , 在一组序列中选出pi,pj,pk (i <= j <= k)使得 p * pi + q * pj + r * pk的值最大
DP
#include
#include
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) > (b) ? (b) : (a))
typedef long long ll;
const int maxn = 1e5 + 5;
const ll INF = 8e18;
ll n, p, q, r, dp[3][maxn], a[maxn];
int main() {
scanf("%lld%lld%lld%lld", &n, &p, &q, &r);
dp[0][0] = -INF;
dp[1][0] = -INF;
dp[2][0] = -INF;
for (int i = 1; i <= n; i++) {
scanf("%lld", a + i);
dp[0][i] = max(dp[0][i - 1], p * a[i]);
//前面表示不要当前位上的数字 后面一个表示要i位置上的数
dp[1][i] = max(dp[1][i - 1], dp[0][i] + q * a[i]);
dp[2][i] = max(dp[2][i - 1], dp[1][i] + r * a[i]);
}
printf("%lld", dp[2][n]);
}
线段树
#include
#define max(a, b) ((a) > (b) ? (a) : (b))
#define min(a, b) ((a) > (b) ? (b) : (a))
typedef long long ll;
const int maxn = 1e5 + 5;
const ll INF = 8e18;
ll n, p, q, r;
ll maxv[maxn << 2], minv[maxn << 2], a[maxn];
void build(int id, int l, int r) {
if (l == r) {
maxv[id] = minv[id] = a[l];
return;
}
int mid = (l + r) >> 1;
build(id << 1, l, mid);
build(id << 1 | 1, mid + 1, r);
//统计开着灯的数量
maxv[id] = max(maxv[id << 1], maxv[id << 1 | 1]);
minv[id] = min(minv[id << 1], minv[id << 1 | 1]);
}
ll queryMax(int id, int l, int r, int x, int y) {
if (x <= l && r <= y) {
return maxv[id];
}
int mid = (l + r) >> 1;
ll ans = -INF;
if (x <= mid) ans = max(ans, queryMax(id << 1, l, mid, x, y));
if (y > mid) ans = max(ans, queryMax(id << 1 | 1, mid + 1, r, x, y));
return ans;
}
ll queryMin(int id, int l, int r, int x, int y) {
if (x <= l && r<= y) {
return minv[id];
}
int mid = (l + r) >> 1;
ll ans = INF;
if (x <= mid) ans = min(ans, queryMin(id << 1, l, mid, x, y));
if (y > mid) ans = min(ans, queryMin(id << 1 | 1, mid + 1, r, x, y));
return ans;
}
int main() {
scanf("%lld%lld%lld%lld", &n, &p, &q, &r);
for (int i = 1; i <= n; i++) {
scanf("%lld", a + i);
}
build(1, 1, n);
ll ans = -INF;
for (int i = 1; i <= n; i++) {
ll tem = 0;
if (p <= 0) {
//选一个最小的数 【1,i】
tem = p * queryMin(1, 1, n, 1, i);
} else {
tem = p * queryMax(1, 1, n, 1, i);
}
tem += q * a[i];
if (r > 0) {
tem += r * queryMax(1, 1, n, i, n);
} else {
tem += r * queryMin(1, 1, n, i, n);
}
ans = max(ans, tem);
}
printf("%lld", ans);
return 0;
}