COFO::1637D Yet Another Minimization Problem

Problem

Point

Design

Thought process

open/close
vector oriA, oriB;
map<string, ll> dp;

ll dynamic (string s, int i, bool f, ll sa, ll sb, vector a, vector b) {
	if (i == n) {
		return (sa + sb);
	}
	ll ns = s +  (f == false ? "0" : "1") ;
	if (dp.find(ns) != dp.end()) return dp[ns];
	
	// current = no swap
	ll ta = 0, tb = 0;
	ll x = (f == false ? oriA[i] : oriB[i] ), y = (f == false ? oriB[i] : oriA[i]);
	
	rep(j, 0, i-1) {
		ta += (a[j] + x)^2;
		tb += (b[j] + y)^2;
	}
	a.push_back(x), b.push_back(x);
	ll ret = dynamic(ns , i + 1, f, sa + ta, sb + tb, a, b );
	ret = min(ret, dynamic(ns, i + 1, !f, sa + ta, sb + tb, a, b);
	a.pop_back(), b.pop_back();
	
	return dp[ns ] = ret;
}

int main() {
	int n; cin >> n;
	oriA.resize(n), oriB.resize(n);
	rep(i, 0, n) cin >> oriA[i];
	rep(i, 0, n) cin >> oriB[i];
	
	vector a, b;
	
	ll ret = dynamic( "", 0, false, 0, 0, a, b);
	ret = min(ret, dynamic( "", 0, true, 0, 0, a, b);
	
	cout << ret << '\n';
}
</pre>

</details>

### Complexity
- O(100 * 10000)

### Code

```cpp
#include<bits/stdc++.h>
#define fi first
#define se second
#define sz(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define rep(i, a, b) for(int i = (a); i <(b); i++)
#define r_rep(i, a, b) for(int i = (a); i >(b); i--)
typedef long long ll;
using namespace std;

bool dp[109][10009];
void solve() {
    int n; cin >> n;
    vector a(n + 1), b(n + 1);
    ll allsum = 0;
    rep(i, 1, n + 1) {
        cin >> a[i];
        allsum += a[i];
    }
    rep(i, 1, n + 1) {
        cin >> b[i];
        allsum += b[i];
    }
    ll square_sum = 0;
    rep(i, 1, n + 1) square_sum += (a[i] * a[i]) + (b[i] * b[i]);
    
    memset(dp, false, sizeof(dp[0]) * (n + 2));
    
    dp[0][0] = true;
    rep(i, 1, n + 1) {
        rep(j, 0, 10000 + 1) {
            if (j - a[i] >= 0 && dp[i-1][j - a[i]]) dp[i][j] = true;
            if (j - b[i] >= 0 && dp[i-1][j - b[i]]) dp[i][j] = true;
        }
    }
    ll mn = 1e12;
    rep(j, 0, 10000 + 1) if (dp[n][j]) {
        ll s1 = j;
        ll s2 = allsum - s1;
        ll s = s1 * s1 + s2 * s2;
        mn = min(mn, s);
    }
    
    ll ans = (n-2) * square_sum + mn;
    cout << ans << '\n';
}

int main(){
    ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
    
    int tc; cin >> tc; while(tc--)
        solve();
    return 0;
}
```