Did I fakesolve?

So I’m doing this problem here, and my code is as follows:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

using std::cout;
using std::endl;
using std::vector;
using std::pair;

/**
 * https://oj.uz/problem/view/NOI18_knapsack
 * 15 5
 * 4 12 1
 * 2 1 1
 * 10 4 1
 * 1 1 1
 * 2 2 1 should output 15
 */
int main() {
    int limit;
    int type_num;
    std::cin >> limit >> type_num;
    
    std::map<int, vector<pair<int, int>>> by_weight;
    for (int t = 0; t < type_num; t++) {
        int value;
        int weight;
        int amt;
        std::cin >> value >> weight >> amt;
        if (weight <= limit && 0 < amt) {
            by_weight[weight].push_back({value, amt});
        }
    }
   
    vector<vector<long long>> best(by_weight.size() + 1,
                                   vector<long long>(limit + 1, INT32_MIN));
    best[0][0] = 0;
    int at = 1;
    for (const auto& [w, items] : by_weight) {
        std::sort(items.begin(), items.end(), std::greater<pair<int, int>>());
        for (int i = 0; i <= limit; i++) {
            best[at][i] = best[at - 1][i];
            int copies = 0;
            int type_at = 0;
            int curr_used = 0;
            long long profit = 0;
            while ((copies + 1) * w <= i && type_at < items.size()) {
                copies++;
                profit += items[type_at].first;
                if (best[at - 1][i - copies * w] != INT32_MIN) {
                    best[at][i] = std::max(
                        best[at][i],
                        best[at - 1][i - copies * w] + profit
                    );
                }
                
                curr_used++;
                if (curr_used == items[type_at].second) {
                    curr_used = 0;
                    type_at++;
                }
            }
        }
        at++;
    }
    cout << *std::max_element(std::begin(best.back()),
                              std::end(best.back())) << endl;
}

It basically groups the items by weight, and then does the standard knapsack DP. However, even though its complexity shouldn’t allow it to pass, I still get all test cases on this. Does anyone know why?

Looks fine to me. What do you think the time complexity is?

It should be O(W^2\cdot \text{something}), and given that W^2 is already 4 million, I don’t think anything above a factor of 10 would work for something.

…bump?

An item of weight i contributes an additive factor of \frac{S^2}{i} to the runtime. Summing over all i from 1 to S gives S^2\cdot \left(\frac{1}{1}+\frac{1}{2}+\cdots+\frac{1}{S}\right)\approx S^2\log S.

1 Like