发现 很大 却很小,而且还是完全背包,一般都是同余最短路。
- 首先考虑贪心,发现对于最优解的很大一部分容量,都是在取性价比最高的物品。令性价比最高的物品为 ,其体积为 ,价值为 。
- 容易发现对于一些总体积为 的物品,不如换成 。因为 是性价比最高的。但是对于总体积不为 就不一定,最优解可能会比全部取 并空出剩下容量要优或劣(劣是因为本题要求总体积必须为 )。考虑求出要优或劣多少。
- 考虑 dp,设 为体积, 为价值,设 为 下最大的 ,也就是最优解比全部取 优或劣多少。可以证明 不会大于实际询问的 。
- 发现 dp 有后效性,建图跑最长路模拟 dp 即可求出。
- 询问的结果即 。
一些性质的说明:
- 关于为什么 dp 中的 不会大于实际询问的 :记实际询问的 为 ,把 dp 过程看成一条最长路,那么这条最长路就不会两次经过同一个结点,不然把两次经过该结点中间使用的一些物品换成 更优。所以 dp 中的 。观察发现这题 ,所以可证。
- 关于为什么没有正环,感性理解一下,最长路在模拟 dp,而这个 dp 的值有上限。
理论最坏复杂度是 ,但是在本题的图里面 SPFA 跑得飞快,而且出题人不太能卡()
同余最短路,345ms。
#include <bits/stdc++.h>
using namespace std;
namespace Milkcat {
typedef long long LL;
const int N = 1e6 + 5, M = 5e6 + 5;
struct edge {
LL to, w, next;
} e[M];
queue<LL> q;
LL n, m, t, T, V, cnt, w[N], v[N], head[N], dis[N];
bool vis[N];
void add(LL u, LL v, LL w) {
e[++ cnt].to = v;
e[cnt].w = w;
e[cnt].next = head[u];
head[u] = cnt;
}
void SPFA(int s) { // SPFA 求最长路
for (int i = 0; i <= m; i ++) dis[i] = -1e18;
dis[s] = 0, q.push(s);
while (!q.empty()) {
int u = q.front(); q.pop();
vis[u] = false;
for (int i = head[u]; i; i = e[i].next) {
int v = e[i].to;
if (dis[v] < dis[u] + e[i].w) {
dis[v] = dis[u] + e[i].w;
if (!vis[v]) q.push(v), vis[v] = true;
}
}
}
}
int main() {
cin >> n >> T, m = 1e6;
for (int i = 1; i <= n; i ++) {
cin >> w[i] >> v[i];
if (v[i] * m > t * w[i]) m = w[i], t = v[i];
}
for (int i = 0; i <= m; i ++)
for (int j = 1; j <= n; j ++)
add(i, (i + w[j]) % m, v[j] - (i + w[j]) / m * t);
SPFA(0);
for (int i = 1; i <= T; i ++) {
cin >> V;
if (dis[V % m] <= -1e17) cout << "-1\n";
else cout << V / m * t + dis[V % m] << '\n';
}
return 0;
}
}
int main() {
return Milkcat::main();
}