# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
1261751 | mentarios | Knapsack (NOI18_knapsack) | C++17 | 1 ms | 328 KiB |
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXS = 2001;
ll dp[MAXS];
// Usamos arrays para simular a deque para máxima performance
pair<ll, int> dq[MAXS];
int main() {
int S, N;
scanf("%d %d", &S, &N);
for (int i = 0; i < N; i++) {
int v, w, k; // Valor, Peso, Quantidade
scanf("%d %d %d", &v, &w, &k);
if (w == 0) continue; // Itens com peso 0 são um caso especial, aqui vamos ignorá-los
// Unificando a lógica: se k é grande, limitamos ao máximo que cabe
if (k > S / w) {
k = S / w;
}
// Otimização com Fila Monotônica
for (int rem = 0; rem < w; rem++) {
int head = 0, tail = -1; // Início e fim da nossa deque manual
for (int q = 0, j = rem; j <= S; j += w, q++) {
// Remove da frente (head) os estados que estão fora da "janela" de k itens
if (head <= tail && dq[head].second < q - k) {
head++;
}
// Calcula o valor da DP usando o melhor da janela
if (head <= tail) {
dp[j] = max(dp[j], dq[head].first + (ll)q * v);
}
// Prepara o valor atual para ser inserido na fila
ll val_para_fila = dp[j] - (ll)q * v;
// Mantém a fila monotônica (decrescente), removendo piores elementos do final (tail)
while (head <= tail && dq[tail].first <= val_para_fila) {
tail--;
}
// Adiciona o elemento no final da fila
tail++;
dq[tail] = {val_para_fila, q};
}
}
}
printf("%lld\n", dp[S]);
return 0;
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |