完全背包
题目意思:给出n个数,问存在最小的和给出数等价的数集合中元素个数。
那么根据题目中给出的等价概念,最小的数肯定需要保留,那么是不是只要第二小的数,不是最小的数的倍数那么就也要保留,那么对于第三小的也是如果存在表示第三小,那么第三小也可以舍弃。那么题目就变成了最多需要保留的数的个数。
那就完全可以类比成一个多重背包了,每个数可能无限使用,对于当前处理的数,如果减掉这个以前存在的数,加上当前的值也可以求解。初始化除0是1其余都是0,求解n个数中最少保留的个数即可。
#pragma GCC target("avx,sse2,sse3,sse4,popcnt")
#pragma GCC optimize("O2,Ofast,inline,unroll-all-loops,-ffast-math")
#include <bits/stdc++.h>
using namespace std;
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
typedef long long ll; typedef unsigned long long ull; typedef long double ld;
const ll MOD = 1e9 + 7;
inline ll read() { ll s = 0, w = 1; char ch = getchar(); while (ch < 48 || ch > 57) { if (ch == '-') w = -1; ch = getchar(); } while (ch >= 48 && ch <= 57) s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar(); return s * w; }
inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-'); int cnt = 0; while (tmp > 0) { F[cnt++] = tmp % 10 + '0'; tmp /= 10; } while (cnt > 0)putchar(F[--cnt]); }
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans *= a; b >>= 1; a *= a; } return ans; } ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
inline int lowbit(int x) { return x & (-x); }
const int N = 25000 + 7;
bool dp[N];
int a[105];
int main() {
int T = read();
while (T--) {
memset(dp, 0, sizeof(dp));
int n = read();
for (int i = 1; i <= n; ++i) a[i] = read();
sort(a + 1, a + 1 + n);
dp[0] = 1;
int ans = 0;
for (int i = 1; i <= n; ++i) {
if (!dp[a[i]]) {
++ans;
for (int j = a[i]; j < N; ++j)
dp[j] |= dp[j - a[i]];
}
}
write(ans), putchar(10);
}
return 0;
} 
京公网安备 11010502036488号