Given n objects the ith of each cost ai.
Given q queries in the form of s,a, b.
Count the number of subsets that contains a and b but sum of cost does not exceed s.
K is the sum of all Ai
N,Q,K<=4000
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 160 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 151 |
Given n objects the ith of each cost ai.
Given q queries in the form of s,a, b.
Count the number of subsets that contains a and b but sum of cost does not exceed s.
K is the sum of all Ai
N,Q,K<=4000
Name |
---|
check trick number 3 probably something to do with this
Did you mean trick 5 from that blog? Trick 3 has to do with finding possible subset sums — it doesn't work if you also need to count them. In contrast, trick 5 shows you how to remove elements from a knapsack, which seems exactly like what we would want to do.
i was thinking that since k bounded to 4000 we can solve each query in k*root(k) which might work if we are given 2 seconds but yeah for counting it it doesnot work
Notice that the number of subsets containing elements $$$a_i$$$ and $$$a_j$$$ with $$$\mathrm{sum} \le s$$$ is the same as the number of subsets of the set $$$\{a_1, a_2,\dots, a_n\}\setminus\{a_i, a_j\}$$$ with $$$\mathrm{sum} \le s - a_i - a_j$$$.
First, build an array such that $$$dp[i]$$$ is the number of subsets with $$$\mathrm{sum} = i$$$ for $$$i \in [1, k]$$$. This is a standard dp problem that can be solved in $$$O(nk)$$$.
Now for each query, we would like to remove those two elements from the dp array somehow efficiently. Turns out this is possible: you can remove a single element in $$$O(k)$$$ time. Check out trick 5 from this blog. After the elements have been removed, we have to calculate the sum of some prefix of the dp array. This can be naively done in $$$O(k)$$$. You can then add the two elemwnts back to the knapsack in $$$O(k)$$$ time.
This means that the total time complexity is $$$O(nk + qk) = O((n + q)k)$$$.
I'm pretty sure that I saw this trick in a recent ABC contest on AtCoder.
Yes, I also remember that: ABC321F