結果
| 問題 | No.2026 Yet Another Knapsack Problem |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2026-11-24 21:57:53 |
| 言語 | C++23(gcc16) (gcc 16.2.0 + boost 1.92.0 + ACL) |
| 結果 |
AC
不安定
|
| 実行時間 | 129 ms / 10,000 ms |
| + 672µs | |
| コード長 | 2,220 bytes |
| 記録 | |
| コンパイル時間 | 2,075 ms |
| コンパイル使用メモリ | 186,152 KB |
| 実行使用メモリ | 52,352 KB |
| 最終ジャッジ日時 | 2026-11-24 21:57:59 |
| 合計ジャッジ時間 | 5,658 ms |
|
ジャッジサーバーID (参考情報) |
judge4_0 / judge1_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 44 |
ソースコード
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const long long NEG_INF = -4e18;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
if (!(cin >> N)) return 0;
vector<int> c(N + 1);
vector<long long> v(N + 1);
for (int i = 1; i <= N; ++i) {
cin >> c[i] >> v[i];
}
// dp[cnt][w]: 恰好选 cnt 个物品、总重量恰好为 w 的最大价值
vector<vector<long long>> dp(N + 1, vector<long long>(N + 1, NEG_INF));
dp[0][0] = 0;
// 手写数组模拟单调队列,常数更小
vector<int> q_idx(N + 1);
vector<long long> q_val(N + 1);
// 核心:按重量从大到小枚举物品
for (int i = N; i >= 1; --i) {
int limit = c[i];
long long vi = v[i];
// 枚举不变量 d = w - cnt * i
for (int d = 0; d <= N; ++d) {
int head = 0, tail = 0;
int max_cnt = (N - d) / i;
for (int cnt = 0; cnt <= max_cnt; ++cnt) {
int w = d + cnt * i;
long long old_val = dp[cnt][w];
// 1. 若旧状态可达,先尝试入队(维持队列单调递减)
if (old_val > NEG_INF / 2) {
long long key = old_val - cnt * vi;
while (head < tail && q_val[tail - 1] <= key) {
--tail;
}
q_idx[tail] = cnt;
q_val[tail] = key;
++tail;
}
// 2. 弹出超出数量限制 [cnt - limit, cnt] 的队首元素
while (head < tail && q_idx[head] < cnt - limit) {
++head;
}
// 3. 原地更新当前状态
if (head < tail) {
dp[cnt][w] = q_val[head] + cnt * vi;
} else {
dp[cnt][w] = NEG_INF;
}
}
}
}
// 统计每个 k 的答案
for (int k = 1; k <= N; ++k) {
long long ans = NEG_INF;
for (int w = k; w <= N; ++w) {
ans = max(ans, dp[k][w]);
}
cout << ans << '\n';
}
return 0;
}