1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <algorithm> #include <utility> #include <vector> #include <istream> #include <map> #include <cmath> #include <stack> #include <set> #include <cstring> #include <string> #define ll long long #define maxn 1000005 #define mdl 998244353 #define clr(a,n) for(int i=0;i<n;i++)a[i]=0 #define cfast std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define pll pair<ll,ll> #define inc(i,a,n) for(int i=a;i<n;i++) #define vset(a,n,m) for(int i=0;i<n;i++)a[i]=m; using namespace std; ll dp[3000],roller[3000],vis[3000]; ll a[10005]; vector<int> hav[10005]; int main(){ cfast; int t; cin >> t; while (t--) { int n; cin >> n; inc(i, 1, n + 1)scanf("%d", &a[i]); hav[1].push_back(0); clr(dp, 3000); dp[0] = 0; ll ans = 1e5; inc(i, 1, n + 1) { vset(roller, 3000, 1e5); clr(vis, 3000); inc(j, 0, hav[i].size()) { int tj = hav[i][j]; if (tj >= a[i]) {
roller[tj - a[i]] = min(roller[tj - a[i]], dp[tj] + a[i]); if (i == n)ans = min(ans, tj-a[i]+roller[tj - a[i]]); if (vis[tj - a[i]] == 0)hav[i+1].push_back(tj - a[i]),vis[tj-a[i]]=1; if (tj + a[i] <= 2000) { roller[tj + a[i]] = min(roller[tj + a[i]], max((ll)0, dp[tj] - a[i])); if (i == n)ans = min(ans, tj + a[i] + roller[tj + a[i]]); if (vis[tj + a[i]] == 0)hav[i + 1].push_back(tj + a[i]), vis[tj + a[i]] = 1; } } else { roller[0] = min(roller[0], dp[tj] + a[i]); if (i == n)ans = min(ans, roller[0]); if (vis[0] == 0)hav[i+1].push_back(0), vis[0] = 1; if (tj + a[i] <= 2000) { roller[tj + a[i]] = min(roller[tj + a[i]], max((ll)0, dp[tj] - a[i])); if (i == n)ans = min(ans, tj + a[i] + roller[tj + a[i]]); if (vis[tj + a[i]] == 0)hav[i + 1].push_back(tj + a[i]), vis[tj + a[i]] = 1; } } } memcpy(dp, roller, 3000 * sizeof(ll)); } cout << ans << endl; inc(i, 1, n + 2)hav[i].clear(); } }
|