P9140 [THUPC 2023 初赛] 背包 题解

· · 题解

\mathcal{Solution}

发现 V 很大 v_i 却很小,而且还是完全背包,一般都是同余最短路。

一些性质的说明:

理论最坏复杂度是 \mathcal{O}(nv^2+q),但是在本题的图里面 SPFA 跑得飞快,而且出题人不太能卡()

\mathcal{Code}

同余最短路,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();
}